Beispiel #1
0
 /// <summary>
 /// Construcor
 /// </summary>
 public GetLIUSBAddress()
     : base(i18n.FlakeComunicationCommands.GetLIUSBAddressName, i18n.FlakeComunicationCommands.GetLIUSBAddressDesc)
 {
     _ByteArray = new byte[] { 255, 254, 242, 1, 0 };
     CommunicationHelper.AddChecksumByteToArray(ref _ByteArray);
     _LogMsg = string.Format(i18n.FlakeComunicationCommandsLogMsgs.GetLIUSBAddress);
 }
Beispiel #2
0
        public KRResponse PostExamResult(ExamResultMetadata <T> result)
        {
            try
            {
                switch (this._type)
                {
                case ProductType.BMD:
                    var bmdTcpService = _proxy as IBMDTcpService;
                    var jsonStr       = CommunicationHelper.SerializeObjToJsonStr(result);
                    if (bmdTcpService != null)
                    {
                        return(bmdTcpService.PostExamResult(jsonStr));
                    }
                    break;

                case ProductType.KRTCD:
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            catch (Exception ex)
            {
                ClientHelper.TraceException("TCPClientManager.PostExamResult", "上传检查结果", ex.Message);
            }
            return(new KRResponse()
            {
                Status = "FAIL", Msg = ""
            });
        }
Beispiel #3
0
        private string getOutPath()
        {
            var sb = new StringBuilder(200);

            CommunicationHelper.GetPrivateProfileString(XML_CONFIG_SECTION, XML_CONFIG_OUTPATH, "", sb, 200, _configPath);
            return(sb.ToString().Trim());
        }
Beispiel #4
0
        public override Patient_DTO GetPatient(string patientId)
        {
            try
            {
                var patientUrl = Config.HttpConfigModel.PatientUrl;
                CommunicationHelper.RecordTrace("GetPatient", $"开始获取病人{patientId}的信息");
                Patient_DTO patient = null;
                if (_helper == null)
                {
                    return(null);
                }
                CommunicationHelper.RecordTrace("GetPatient", $"获取病人信息地址为{patientUrl}");
                string url = string.Empty;

                if (patientUrl.EndsWith("=") || patientUrl.EndsWith("/"))
                {
                    url = patientUrl + patientId;
                }
                else
                {
                    url = patientUrl + "/" + patientId;
                }

                var finalUrl = AddToken(url);

                _helper.NeedUrlDecode = NeedUrlDecode;
                patient = _helper.HttpGetData <Patient_DTO>(finalUrl);
                return(patient);
            }
            catch (KRException ex)
            {
                throw new Exception(ex.Msg);
            }
        }
Beispiel #5
0
        private void RunUntappd(string filePath)
        {
            FileStatus fileStatus = FileHelper.Check(filePath, Extensions.GetSupportExtensions());

            if (!EnumsHelper.IsValidFileStatus(fileStatus))
            {
                interactionRequestService.ShowMessage(Properties.Resources.Warning, CommunicationHelper.GetFileStatusMessage(fileStatus, filePath));
                return;
            }
            try
            {
                string untappdUserName = String.Empty;
                if (FileHelper.GetExtensionWihtoutPoint(filePath).Equals(Extensions.CSV))
                {
                    if (!interactionRequestService.AskReplaceText(Properties.Resources.UntappdUserNameCaption, ref untappdUserName))
                    {
                        return;
                    }
                }

                untappdService.Initialize(filePath, untappdUserName);
            }
            catch (ArgumentException ex)
            {
                interactionRequestService.ShowError(Properties.Resources.Error, StringHelper.GetFullExceptionMessage(ex));
                return;
            }

            settingService.SetRecentFilePaths(FileHelper.AddFilePath(settingService.GetRecentFilePaths(), filePath, settingService.GetMaxRecentFilePaths()));
            moduleManager.LoadModule(typeof(MainModule).Name);
            ActivateView(RegionNames.RootRegion, typeof(Main));
            interactionRequestService.ShowMessageOnStatusBar(filePath);
        }
 public void ExecSend(string cloudData, string url)
 {
     if (!string.IsNullOrEmpty(cloudData))
     {
         CommunicationHelper.SendData(cloudData, url, CommonVariate.Cloud_URL_Method_Add);
     }
 }
 /// <summary>
 /// Construcor
 /// </summary>
 /// <param name="extAddress">Extended address of locomotive</param>
 public GetLocomotiveFunctionTypesLo(HiLoAddress extAddress)
     : base(i18n.FlakeComunicationCommands.GetLocomotiveFunctionTypesLoName, i18n.FlakeComunicationCommands.GetLocomotiveFunctionTypesLoDesc)
 {
     _ByteArray = new byte[] { 255, 254, 227, 7, (byte)extAddress.Address_Hi, (byte)extAddress.Address_Lo };
     CommunicationHelper.AddChecksumByteToArray(ref _ByteArray);
     _LogMsg = string.Format(i18n.FlakeComunicationCommandsLogMsgs.GetLocomotiveFunctionTypesLo, extAddress.Address.ToString());
 }
        public TOut HttpGetData <TOut>(string url, HttpItem pitem = null)
        {
            //encoder = encoder ?? Encoding.UTF8;
            try
            {
                var resultStr = HttpGetData(url, pitem);
                return(CommunicationHelper.DeserializeJsonToObj <TOut>(resultStr));

                //var client = new KRWebClient();
                ////client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                //client.Timeout = Timeout;
                //var strContent = DecodeResponseStr(client.DownloadString(url));
                //Trace.WriteLine("HttpGetData返回数据:" + strContent);
                //return CommunicationHelper.DeserializeJsonToObj<TOut>(strContent);

                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                //request.Method = "GET";
                //request.ContentType = "Content-Type = application/json";
                //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //Stream myResponseStream = response.GetResponseStream();
                //StreamReader myStreamReader = new StreamReader(myResponseStream, _encoding);
                //retString = myStreamReader.ReadToEnd();
                //myStreamReader.Close();
                //myResponseStream.Close();
            }
            catch (Exception ex)
            {
                ClientHelper.TraceException("HttpPostData:Get", "Get数据失败", ex.Message);
                return(default(TOut));
            }
        }
        public string HttpGetData(string url, HttpItem pitem = null)
        {
            try
            {
                var httpItem = pitem ?? new HttpItem()
                {
                    URL = url
                };

                var result     = _engine.GetHtml(httpItem);
                var strContent = result.Html;
                CommunicationHelper.RecordTrace("HttpGetData", "返回的数据" + result.Html);
                return(strContent);
                //string retString = string.Empty;
                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                //request.Method = "GET";
                //request.ContentType = "Content-Type = application/json";
                //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                //Stream myResponseStream = response.GetResponseStream();
                //StreamReader myStreamReader = new StreamReader(myResponseStream, encoder);
                //retString = myStreamReader.ReadToEnd();
                //myStreamReader.Close();
                //myResponseStream.Close();
                //return DecodeResponseStr(retString);
            }
            catch (Exception ex)
            {
                ClientHelper.TraceException("HttpPostData:Get", "Get数据失败", ex.Message);
                return(string.Empty);
            }
        }
 /// <summary>
 /// Construcor
 /// </summary>
 /// <param name="extAddress">Adress of locomotive</param>
 /// <param name="mode">Startmode for central</param>
 public SetLFunctionRefreshMode(HiLoAddress extAddress, Base.Enums.LocoFunctionRefreshMode.LocoFunctionRefreshMode mode)
     : base(i18n.FlakeComunicationCommands.SetLFunctionRefreshModeName, i18n.FlakeComunicationCommands.SetLFunctionRefreshModeDesc)
 {
     _ByteArray = new byte[] { 255, 254, 228, 47, (byte)extAddress.Address_Hi, (byte)extAddress.Address_Lo, (byte)mode };
     CommunicationHelper.AddChecksumByteToArray(ref _ByteArray);
     _LogMsg = string.Format(i18n.FlakeComunicationCommandsLogMsgs.SetLFunctionRefreshMode, new Base.Enums.LocoFunctionRefreshMode.LocoFunctionRefreshModeExtended(mode).Name, extAddress.Address.ToString());
 }
Beispiel #11
0
        public void SaveReportMetadata <T>(ExamResultMetadata <T> reportMetadata) where T : BaseCheckResult
        {
            var         outPath = getOutPath();
            var         xml     = CommunicationHelper.SerializerToXml(reportMetadata);
            XmlDocument doc     = new XmlDocument();

            doc.LoadXml(xml);
            doc.Save(outPath + "Report_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + ".xml");
        }
Beispiel #12
0
 public AboutViewModel(IUntappdService untappdService)
 {
     this.untappdService = untappdService;
     Version             = CommunicationHelper.GetTitle();
     if (untappdService.IsUNTPProject())
     {
         ImagePaths = GetImagePaths();
     }
 }
Beispiel #13
0
        /// <summary>
        /// Initializes a new instance of the FlashlightHelper class.
        /// </summary>
        /// <param name="communicationHelper">
        /// Класс для взаимодействия с головой робота.
        /// </param>
        public FlashlightHelper(CommunicationHelper communicationHelper)
        {
            if (communicationHelper == null)
            {
                throw new ArgumentNullException("communicationHelper");
            }

            this.communicationHelper = communicationHelper;
        }
Beispiel #14
0
        /// <summary>
        /// Construcor
        /// </summary>
        /// <param name="mode">Startmode for central</param>
        public SetLCentralStartMode(Base.Enums.CentralStartMode.CentralStartMode mode)
            : base(i18n.FlakeComunicationCommands.SetLCentralStartModeName, i18n.FlakeComunicationCommands.SetLCentralStartModeDesc)
        {
            byte databyte = (byte)Base.FlakeHelper.ConvertBinaryStringToDecimal(string.Format("00000{0}00", (mode == Base.Enums.CentralStartMode.CentralStartMode.auto) ? ("1") : ("0")));

            _ByteArray = new byte[] { 255, 254, 34, 34, databyte };
            CommunicationHelper.AddChecksumByteToArray(ref _ByteArray);
            _LogMsg = string.Format(i18n.FlakeComunicationCommandsLogMsgs.SetLCentralStartMode, new Base.Enums.CentralStartMode.CentralStartModeExtended(mode).Name);
        }
Beispiel #15
0
 /// <summary>
 /// Construcor
 /// </summary>
 /// <param name="extAddress">Extended address of locomotive</param>
 /// <param name="speedValue">Speed of locomotive to be set</param>
 /// <param name="driveForward">use forward direction</param>
 /// <param name="speedSections">speed section setup of locomotive</param>
 public LocomotiveDrive(HiLoAddress extAddress, int speedValue, bool driveForward, Base.Enums.LocomotiveSpeedSections.LocomotiveSpeedSections speedSections)
     : base(i18n.FlakeComunicationCommands.DriveCommandName, i18n.FlakeComunicationCommands.DriveCommandDesc)
 {
     _ByteArray = new byte[] { 255, 254, 228, GetIdentifier(speedSections), (byte)extAddress.Address_Hi,
                               (byte)extAddress.Address_Lo, GetSpeedAndDirection(speedValue, driveForward, speedSections) };
     CommunicationHelper.AddChecksumByteToArray(ref _ByteArray);
     _LogMsg = string.Format(i18n.FlakeComunicationCommandsLogMsgs.DriveCommand, extAddress.Address.ToString(), speedValue.ToString(), (driveForward) ?
                             (new Base.Enums.LocomotiveDirection.LocomotiveDirectionExtended(Base.Enums.LocomotiveDirection.LocomotiveDirection.forward).Name) :
                             (new Base.Enums.LocomotiveDirection.LocomotiveDirectionExtended(Base.Enums.LocomotiveDirection.LocomotiveDirection.backward).Name));
 }
Beispiel #16
0
        protected VisualizerInstanceInfo LaunchNewInstance()
        {
            // TODO: don't hardcode this / configure this somehow?
            var exePath = @"C:\Users\joshua.webb\Documents\Visual Studio 2015\Projects\AsyncDebuggerVisualizerTest\AsyncDebuggerVisualizerTest\bin\Debug\AsyncDebuggerVisualizerTest.App.exe";
            var process = Process.Start(exePath);

            CommunicationHelper.WaitForProcessToStartListeningOnAPort(process.Id);

            var newInstances     = FindVisualizerInstances();
            var launchedInstance = newInstances.Single(i => i.ProcessId == process.Id);

            return(launchedInstance);
        }
Beispiel #17
0
        protected override void Activate()
        {
            base.Activate();
            TreeRegionWidth = new GridLength(settingService.GetTreeRegionWidth());

            moduleManager.LoadModule(typeof(TreeModue).Name);
            ActivateView(RegionNames.TreeRegion, typeof(Tree));

            if (!String.IsNullOrEmpty(untappdService.FilePath))
            {
                interactionRequestService.ShowMessageOnStatusBar(CommunicationHelper.GetLoadingMessage(untappdService.FilePath));
            }
        }
Beispiel #18
0
 /// <summary>
 /// Deletes an existing printmark
 /// </summary>
 /// <returns></returns>
 public bool Delete()
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], PrintmarkID [required], Callback, Pretty, Strict
     var resp = ch.ExecuteMethod<SmugMugResponse>("smugmug.printmarks.delete", basic, "PrintmarkID", id);
     if (resp.stat == "ok")
         return true;
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
        private async void DownloadFiles()
        {
            List <Checkin> checkins = untappdService.GetCheckins();
            int            count    = checkins.Count;
            int            counter  = 1;

            foreach (Checkin checkin in checkins)
            {
                interactionRequestService.ShowMessageOnStatusBar(CommunicationHelper.GetLoadingMessage($"{counter++}/{count} -> {checkin.Beer.Name}"));
                await Task.Run(() => DownloadFiles(checkin));
            }
            interactionRequestService.ShowMessageOnStatusBar(CommunicationHelper.GetLoadingMessage(untappdService.FilePath));
        }
Beispiel #20
0
        /// <summary>
        /// Initialization of communication with robot through COM-port.
        /// </summary>
        private void InitializeComPortCommunication()
        {
            this.communicationHelper = new ComPortCommunicationHelper(
                this.settingsHelper.Settings.ComPort,
                this.settingsHelper.Settings.BaudRate,
                this.settingsHelper.Settings.SingleMessageRepetitionsCount);
            this.communicationHelper.TextReceived += this.OnTextReceived;

            this.commandProcessor = new CommandProcessor(
                this.textBoxSend,
                this.historyBox,
                this.communicationHelper,
                this.commandHistory);
        }
Beispiel #21
0
        public void SetPort(int port)
        {
            MyPort = port;
            Invoke(new Action(
                       () =>
            {
                Text = $"Port: {port}";
                SetLabel($"Port: {port}");
                listeningForDataToolStripMenuItem.Checked = true;
            }));

            WaitHandle?.Dispose();
            WaitHandle = CommunicationHelper.LetDudeKnowWereListeningOnSomePort(Process.GetCurrentProcess().Id);
        }
Beispiel #22
0
        /// <summary>
        /// Initialization of communication with robot through UDP-socket.
        /// </summary>
        private void InitializeUdpCommunication()
        {
            this.communicationHelper = new UdpCommunicationHelper(
                this.settingsHelper.Settings.RoboHeadAddress,
                this.settingsHelper.Settings.UdpSendPort,
                this.settingsHelper.Settings.UdpReceivePort,
                this.settingsHelper.Settings.SingleMessageRepetitionsCount);
            this.communicationHelper.TextReceived += this.OnTextReceived;

            this.commandProcessor = new CommandProcessor(
                this.textBoxSend,
                this.historyBox,
                this.communicationHelper,
                this.commandHistory);
        }
Beispiel #23
0
        /// <summary>
        /// Initializes a new instance of the GunHelper class.
        /// </summary>
        /// <param name="communicationHelper">
        /// Объект для взаимодействия с головой робота.
        /// </param>
        /// <param name="controlSettings">
        /// Опции управления роботом.
        /// </param>
        public GunHelper(CommunicationHelper communicationHelper, ControlSettings controlSettings)
        {
            if (communicationHelper == null)
            {
                throw new ArgumentNullException("communicationHelper");
            }

            if (controlSettings == null)
            {
                throw new ArgumentNullException("controlSettingsHelper");
            }

            this.communicationHelper = communicationHelper;
            this.controlSettings     = controlSettings;
        }
        private async void UploadProjectPhotosAsync(List <long> checkinIds, string uploadDirectory)
        {
            for (int i = 0; i < checkinIds.Count; i++)
            {
                Checkin checkin = untappdService.GetCheckin(checkinIds[i]);
                if (checkin == null || String.IsNullOrEmpty(checkin.UrlPhoto))
                {
                    continue;
                }

                string message = $"{Properties.Resources.Loading} {i + 1}/{checkinIds.Count}: {checkin.UrlPhoto}";
                interactionRequestService.ShowMessageOnStatusBar(message);
                await Task.Run(() => UploadCheckinPhoto(checkin, uploadDirectory));
            }
            interactionRequestService.ShowMessageOnStatusBar(CommunicationHelper.GetLoadingMessage(untappdService.FilePath));
        }
Beispiel #25
0
        public void InitializeService(string configPath = null)
        {
            _configPath = string.IsNullOrEmpty(configPath) ? DEFAULT_CONFIG_PATH : configPath;
            if (!File.Exists(_configPath))
            {
                ExceptionEvent?.Invoke(new KRException("InitializeService", "配置文件丢失", "配置文件不存在,请核对"));
            }
            var sb = new StringBuilder(200);

            CommunicationHelper.GetPrivateProfileString(XML_CONFIG_SECTION, XML_CONFIG_INPATH, "", sb, 200, _configPath);
            InPath = sb.ToString().Trim();
            if (!Directory.Exists(InPath))
            {
                ExceptionEvent?.Invoke(new KRException("InitializeService", "客户信息目录异常", "找不到客户信息目录,请核对后重试"));
            }
        }
Beispiel #26
0
 private void BuildHttpItem(ExamResultMetadata <T> checkResult, HttpItem pitem, string postResultUrl, string parameterName)
 {
     pitem.URL = postResultUrl;
     if (string.IsNullOrEmpty(parameterName))
     {
         pitem.Postdata    = CommunicationHelper.SerializeObjToJsonStr(checkResult);
         pitem.ContentType = "application/json";
     }
     else
     {
         pitem.Postdata = AddToken(string.Format("{0}={1}", parameterName,
                                                 CommunicationHelper.SerializeObjToJsonStr(checkResult)));
         pitem.ContentType  = "application/x-www-form-urlencoded";
         pitem.PostEncoding = Encoding.UTF8;
     }
 }
Beispiel #27
0
        /// <summary>
        /// Gets the access token.
        /// </summary>
        /// <returns>Task&lt;System.String&gt;.</returns>
        /// <exception cref="CommunicationException"></exception>
        public async Task <AuthenticationHeaderValue> GetAuthenticationHeader()
        {
            if (_userName == null)
            {
                // no point in looking if the username hasn't been set up
                return(null);
            }

            if (_cachedAuthenticationHeader != null && DateTime.UtcNow < _tokenExpiryDateUtc)
            {
                // used the cached token;
                return(_cachedAuthenticationHeader);
            }
            else
            {
                Dictionary <string, string> postValues = new Dictionary <string, string>();

                postValues["grant_type"] = "password";
                postValues["username"]   = _userName;
                postValues["password"]   = _password;

                var timeoutSeconds = _settingsService.Setting <int?>("Communication.TimeoutSeconds");
                var timeout        = (timeoutSeconds.HasValue)
                                                                                ? (TimeSpan?)TimeSpan.FromSeconds(timeoutSeconds.Value)
                                                                                : null;

                var communicationHelper = new CommunicationHelper <LoginResponse, LoginErrorResponse> {
                    Timeout = timeout
                };

                var loginResponse = await communicationHelper.PostRequest(_urlHelper.BuildUrl("oauth2/token"), postValues);

                if (loginResponse == null)
                {
                    throw new CommunicationException(communicationHelper.ErrorResponse?.ToString());
                }
                else
                {
                    _cachedAuthenticationHeader = new AuthenticationHeaderValue("Bearer", loginResponse.AccessToken);

                    // remember the expiry date, but give ourselves a bit of leeway with the time
                    _tokenExpiryDateUtc = DateTime.UtcNow + TimeSpan.FromSeconds(loginResponse.ExpiresInSeconds.Value) - TimeSpan.FromMinutes(2);

                    return(_cachedAuthenticationHeader);
                }
            }
        }
Beispiel #28
0
        /// <summary>
        /// Processes command in the command line control.
        /// </summary>
        public void ProcessCommand()
        {
            this.commandHistory.Add(this.commandLineTextBox.Text);

            IEnumerable <string> commands = CommunicationHelper.ParseRoboScript(this.commandLineTextBox.Text);

            var notSentCommands = new List <string>();

            foreach (string command in commands)
            {
                // Пустышки в сторону!
                if (command.Trim().Equals(string.Empty))
                {
                    continue;
                }

                // Если есть ошибка, то все последующие команды не посылаются роботу.
                if (notSentCommands.Count > 0)
                {
                    notSentCommands.Add(command);
                }
                else
                {
                    bool sendResult = this.SendMessageToRobot(false, command);

                    if (sendResult)
                    {
                        this.historyBox.AppendTextSentToRobot(this.communicationHelper.LastSentMessage);
                    }
                    else
                    {
                        this.historyBox.AppendTextSentToRobot(string.Format("Ошибка в {0}: {1}", command, this.communicationHelper.LastErrorMessage));
                        notSentCommands.Add(command);
                    }
                }
            }

            // В поле ввода команд оставляем только неотправленные команды.
            if (notSentCommands.Count > 0)
            {
                this.commandLineTextBox.Text = GenerateCommandLine(notSentCommands);
            }
            else
            {
                this.commandLineTextBox.Text = string.Empty;
            }
        }
Beispiel #29
0
        private void Activate()
        {
            Title = CommunicationHelper.GetTitle();
            bool   isUsedArgument = false;
            string filePath;

            if (argumentsProvider.Arguments.Count > 0)
            {
                filePath       = argumentsProvider.Arguments[0];
                isUsedArgument = true;
            }
            else
            {
                filePath = FileHelper.GetFirstFileItemPath(settingService.GetRecentFilePaths());
            }

            FileStatus fileStatus = FileHelper.Check(filePath, Extensions.GetSupportExtensions());

            if (EnumsHelper.IsValidFileStatus(fileStatus))
            {
                try
                {
                    untappdService.Initialize(filePath);
                    if (isUsedArgument)
                    {
                        settingService.SetRecentFilePaths(FileHelper.AddFilePath(settingService.GetRecentFilePaths(), filePath, settingService.GetMaxRecentFilePaths()));
                    }

                    moduleManager.LoadModule(typeof(MainModule).Name);
                }
                catch (ArgumentException ex)
                {
                    interactionRequestService.ShowError(Properties.Resources.Error, StringHelper.GetFullExceptionMessage(ex));
                    moduleManager.LoadModule(typeof(WelcomeModule).Name);
                }
            }
            else
            {
                if (fileStatus != FileStatus.IsEmptyPath)
                {
                    interactionRequestService.ShowMessage(Properties.Resources.Warning, CommunicationHelper.GetFileStatusMessage(fileStatus, filePath));
                }

                moduleManager.LoadModule(typeof(WelcomeModule).Name);
            }
        }
Beispiel #30
0
 public override Patient_DTO GetPatient(string patientId)
 {
     try
     {
         Trace.WriteLine(string.Format("开始获取病人{0}的信息", patientId));
         Trace.WriteLine(string.Format("获取病人信息地址为{0}", Config.HttpConfigModel.PatientUrl));
         var      proxy   = new WebServiceProxy(Config.HttpConfigModel.PatientUrl, Config.HttpConfigModel.WebServiceName);
         string[] param   = { ClientConstants.KR_GET_PATIENT, patientId };
         var      jsonStr = (string)proxy.ExecuteQuery(Config.HttpConfigModel.WebServiceName, param);
         Trace.WriteLine(string.Format("获取病人信息为{0}", jsonStr));
         return(CommunicationHelper.DeserializeJsonToObj <Patient_DTO>(jsonStr));
     }
     catch (KRException ex)
     {
         throw new Exception("获取病人信息失败" + ex.Msg);
     }
 }
        public async Task <SessionUpdateResponse> PostSessionUpdateRequestToServer(SessionUpdateRequest sessionUpdateRequest)
        {
            var communicationHelper = new CommunicationHelper <SessionUpdateResponse, ErrorResponse> {
                Timeout = GetTimeout()
            };

            var authenticationHeader = await _accountService.GetAuthenticationHeader();

            var response = await communicationHelper.PostRequest(_urlHelper.BuildUrl("api/Cases/SessionUpdate"), JsonConvert.SerializeObject(sessionUpdateRequest), authenticationHeader);

            if (response == null)
            {
                throw new CommunicationException(communicationHelper.ErrorResponse?.ToStringList());
            }

            return(response);
        }
Beispiel #32
0
 /// <summary>
 /// Authenticates a user based on the specified email address (or nickname) and password
 /// </summary>
 /// <param name="EmailAddress">The email address (or nickname) for the user.</param>
 /// <param name="Password">The password for the user.</param>
 /// <param name="Extras">A comma separated string of additional attributes to return in the response</param>
 /// <returns>Login (AccountStatus, Type, FileSizeLimit, PasswordHash, SessionID, SmugVault, User (id, DisplayName, NickName))</returns>
 public MyUser Login(string EmailAddress, string Password, string Extras)
 {
     CommunicationHelper ch = new CommunicationHelper();
     string su;
     // APIKey [required], EmailAddress [required], Password [required], Callback (JSON & PHP responses only), Extras, Pretty, Sandboxed, Strict
     var resp = ch.ExecuteMethod<LoginResponse>("smugmug.login.withPassword", null, out su,"EmailAddress", EmailAddress, "Password", Password, "Extras", Extras);
     if (resp.stat == "ok")
     {
         MyUser u = new MyUser();
         resp.Login.PopulateUser(u);
         u.basic._su = su;
         return u;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #33
0
 /// <summary>
 /// Authenticates a user based on the specified user id and password hash.
 /// </summary>
 /// <param name="UserId">The id for a specific user</param>
 /// <param name="PasswordHash">The password hash for the user</param>
 /// <param name="Extras">A comma separated string of additional attributes to return in the response</param>
 /// <returns>Login (AccountStatus, AccountType, FileSizeLimit, SessionID, SmugVault, User (id, DisplayName, NickName, URL))</returns>
 public MyUser Login(int UserId, string PasswordHash, string Extras)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // APIKey [required], Callback, Extras, PasswordHash [required], Pretty, Sandboxed, Strict, UserID [required]
     string su;
     var resp = ch.ExecuteMethod<LoginResponse>("smugmug.login.withHash", null, out su, "UserID", UserId, "PasswordHash", PasswordHash, "Extras", Extras);
     if (resp.stat == "ok")
     {
         MyUser u = new MyUser();
         resp.Login.PopulateUser(u);
         u.basic._su = su;
         return u;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #34
0
 /// <summary>
 /// Adds an album to a specified sharegroup 
 /// </summary>
 /// <param name="AlbumToAdd">Album to be added to the sharegroup.</param>
 /// <returns></returns>
 public async Task<bool> AddAlbumAsync(Album AlbumToAdd)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], ShareGroupID [required], AlbumID [required], Callback, Pretty, Strict 
     var resp = await ch.ExecuteMethod<SmugMugResponse>("smugmug.sharegroups.albums.add", basic, "ShareGroupID", this.id, "AlbumID", AlbumToAdd.id);
     if (resp.stat == "ok")
     {
         if (this.Albums == null)
             this.Albums = new List<Album>();
         // Add the album to the current object
         this.Albums.Add(AlbumToAdd);
         // Increase the no of albums this sharegroup has
         this.AlbumCount++;
         return true;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #35
0
 /// <summary>
 /// Retrieve information for a printmark. 
 /// </summary>
 /// <returns>New printmark object (id, Name, Dissolve, Image struct - id, key; Location)</returns>
 public Printmark GetInfo()
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], PrintmarkID [required], Callback, Pretty, Strict
     var resp = ch.ExecuteMethod<PrintmarkResponse>("smugmug.printmarks.getInfo", basic, "PrintmarkID", id);
     if (resp.stat == "ok")
     {
         var myPrintmark = resp.Printmark;
         myPrintmark.basic = basic;
         return myPrintmark;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #36
0
 /// <summary>
 /// This method will re-sort all the photos inside of the album specified by AlbumID. Note that this is a one-time event, and doesn't apply directly to images added in the future by other means.
 /// </summary>
 /// <param name="b"></param>
 /// <param name="d"></param>
 /// <returns></returns>
 public bool ReSort(By b, Direction d)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], AlbumID [required], By [required], Direction [required], Callback, Pretty, Strict
     var resp = ch.ExecuteMethod<SmugMugResponse>("smugmug.albums.reSort", basic, "AlbumID", id, "By", b.ToString(), "Direction", d.ToString());
     if (resp.stat == "ok")
         return true;
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #37
0
 /// <summary>
 /// Deletes  a specified sharegroup
 /// </summary>
 /// <returns>Returns an empty successful response, if it completes without error</returns>
 public async Task<bool> DeleteAsync()
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], ShareGroupID [required], Callback, Pretty, Strict
     var resp = await ch.ExecuteMethod<SmugMugResponse>("smugmug.sharegroups.delete", basic, "ShareGroupID", id);
     if (resp.stat == "ok")
         return true;
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #38
0
 /// <summary>
 /// Renames an existing subcategory with the given name
 /// </summary>
 /// <param name="Name">The name for the subcategory</param>
 /// <param name="Extras">A comma separated string of additional attributes to return in the response</param>
 /// <returns>Bool (actually returns a SubCategory object with id)</returns>
 public bool Rename(string Name, string Extras)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], SubCategoryID [required], Name [required], Callback, Extras, Pretty, Strict
     var resp = ch.ExecuteMethod<SubCategoryResponse>("smugmug.subcategories.rename", basic, "SubCategoryID", id, "Name", Name, "Extras", Extras);
     if (resp.stat == "ok")
     {
         // If the rename works, change the name of the current object as well
         this.Name = Name;
         return true;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #39
0
 /// <summary>
 /// Establishes an anonymous session.
 /// </summary>
 /// <returns>Login (Session (id))</returns>
 public async Task<MyUser> LoginAsync()
 {
     // APIKey [required], Callback, Pretty, Strict
     CommunicationHelper ch = new CommunicationHelper();
     var resp = await ch.ExecuteMethod<LoginResponse>("smugmug.login.anonymously", null);
     if (resp.stat == "ok")
     {
         MyUser currentUser = new MyUser();
         if (currentUser.basic == null)
             currentUser.basic = new SmugMugBase();
         currentUser.basic.SessionID = resp.Login.Session.id;
         currentUser.basic.NickName = "";
         currentUser.DisplayName = "";
         return currentUser;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #40
0
 /// <summary>
 /// Update on SmugMug a sharegroup modified locally (AccessPassworded, Description, Name, Password, PasswordHint). If any of the parameters are missing or are empty strings "", they're ignored and the current settings are preserved. Otherwise, they're updated with the new settings.
 /// </summary>
 public async Task<bool> ModifyAsync(string Extras)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], ShareGroupID [required], AccessPassworded, Callback, Description, Extras, Name, Password, PasswordHint, Pretty, Strict
     var ls = BuildPropertiesValueList(this, "id", "Tag", "AlbumCount", "Albums", "Passworded", "URL");
     ls.Add("ShareGroupID"); ls.Add(this.id.ToString());
     ls.Add("Extras"); ls.Add(Extras);
     var resp = await ch.ExecuteMethod<SmugMugResponse>("smugmug.sharegroups.modify", basic, ls.ToArray());
     if (resp.stat == "ok")
         return true;
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #41
0
 /// <summary>
 /// Gets the extended transfer statistics for the given Album and all its images during the given Month and Year (id, Key, Bytes, Hits, Large, Medium, original, Small, Thumb, Tiny, X2Large, X3Large, XLarge, Video320, Video640, Video960, Video1280, Video1960, Images array with the same kind of stats). SmugMug only keeps the last few months of traffic on file, so requesting farther back then 2 months may not return valid results. A float is provided for Original and video sizes because it's possible to watch only a portion of a video
 /// </summary>
 /// <param name="Month"></param>
 /// <param name="Year"></param>
 /// <param name="Heavy">If Heavy is set to "1", transfer statistics for each image in each album will be returned as well</param>
 /// <returns></returns>
 public Album GetStats(int Month, int Year, bool Heavy)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], AlbumID [required], Month [required], Year [required], Associative, Callback, Heavy, Pretty, Strict
     var resp = ch.ExecuteMethod<AlbumResponse>("smugmug.albums.getStats", basic, "AlbumID", id, "Month", Month, "Year", Year, "Heavy", Heavy);
     if (resp.stat == "ok")
     {
         var myAlbum = resp.Album;
         myAlbum.basic = basic;
         //Hack: The class has 2 properties with the same name - Comments. I've separated them in 2 different properties (HasComments and CommentsList)
         if (myAlbum.Comments != null)
             myAlbum.HasComments = (bool)myAlbum.Comments;
         return myAlbum;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #42
0
 /// <summary>
 /// Retrieves a list of comments for an album
 /// </summary>
 /// <param name="Associative">Returns an associative array</param>
 /// <param name="LastUpdated">Return results where LastUpdated is after the epoch time provided</param>
 /// <param name="SitePassword">The site password for a specific user</param>
 public void GetComments(bool Associative, int LastUpdated, string SitePassword)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], AlbumID [required], Key [required], Password, Associative, Callback, LastUpdated, Pretty, SitePassword, Strict
     AlbumResponse resp = new AlbumResponse();
     if ((this != null) && !(string.IsNullOrEmpty(this.Password)))
         resp = ch.ExecuteMethod<AlbumResponse>("smugmug.albums.comments.get", basic, "AlbumID", id, "AlbumKey", Key, "SitePassword", SitePassword, "Password", Password, "LastUpdated", LastUpdated, "Associative", Associative);
     else
         resp = ch.ExecuteMethod<AlbumResponse>("smugmug.albums.comments.get", basic, "AlbumID", id, "AlbumKey", Key, "SitePassword", SitePassword, "LastUpdated", LastUpdated, "Associative", Associative);
     if (resp.stat == "ok")
     {
         //Hack: The class has 2 properties with the same name - Comments. I've separated them in 2 different properties (HasComments and CommentsList)
         if (this.CommentsList == null)
             this.CommentsList = new List<Comment>();
         this.CommentsList = (List<Comment>)resp.Album.Comments;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #43
0
        /// <summary>
        /// Change the settings of an existing album - AlbumTemplateID, Backprinting (pro), BoutiquePackaging (pro), CanRank, CategoryID, Clean, ColorCorrection, Comments, CommunityID, DefaultColor  (pro), Description, EXIF, External, FamilyEdit, FriendEdit, Geography, Header (power, pro), HideOwner, HighlightID, Keywords, Larges, NiceName, Originals, PackagingBranding (pro), Password, PasswordHint, Position, Printable, PrintmarkID (pro), ProofDays, Protected (power, pro), Public, Share, SmumugSearchable, SortDirection, SortMethod, SquareThumbs, SubCategoryID, TemplateID, ThemeID, UnsharpAmount (power, pro), UnsharpRadius (power, pro), UnsharpSigma (power, pro), UnsharpThreshold (power, pro), WatermarkID (pro), Watermarking (pro), WorldSearchable, X2Larges, X3Larges, XLarges (pro)
        /// </summary>
        /// <param name="a"></param>
        /// <returns></returns>
        public bool ChangeSettings()
        {
            CommunicationHelper ch = new CommunicationHelper();
            // SessionID [required], AlbumID [required], Callback, Pretty, Strict, AlbumTemplateID, Backprinting (pro), BoutiquePackaging, CanRank,
            // CategoryID, Clean, ColorCorrection, Comments, CommunityID, DefaultColor  (pro), Description, EXIF, External, FamilyEdit,
            // FriendEdit, Geography, Header (power&pro), HideOwner, HighlightID, Keywords, Larges, NiceName, Originals, PackagingBranding, Password,
            // PasswordHint, Position, Printable, PrintmarkID, ProofDays, Protected (power&pro), Public, Share, SmumugSearchable, SortDirection,
            // SortMethod, SquareThumbs, SubCategoryID, TemplateID, ThemeID, UnsharpAmount (power&pro), UnsharpRadius (power&pro), UnsharpSigma (power&pro),
            // UnsharpThreshold (power&pro), WatermarkID (pro), Watermarking (pro), WorldSearchable, X2Larges, X3Larges, XLarges (pro)
            // Hack: The class has 2 properties with the same name - Comments. I've separated them in 2 different properties (HasComments and CommentsList)
            var ls = BuildPropertiesValueList(this, "HasComments", "CommentsList", "Comments","Watermark");
            ls.Add("Comments"); ls.Add(this.HasComments.ToString());
            ls.Add("AlbumID"); ls.Add(this.id.ToString());

            //if there is a watermark, use the id
            if (this.Watermark != null)
            {
                ls.Add("WatermarkID"); ls.Add(this.Watermark.id.ToString());
            }

            if (this.AlbumTemplate != null)
            {
                ls.Add("AlbumTemplateID"); ls.Add(this.AlbumTemplate.id.ToString());
            }

            var resp = ch.ExecuteMethod<AlbumResponse>("smugmug.albums.changeSettings", basic, ls.ToArray());
            if (resp.stat == "ok")
                return true;
            else
            {
                Console.WriteLine(resp.message);
                throw new SmugMugException(resp.code, resp.message, resp.method);
            }
        }
Beispiel #44
0
 /// <summary>
 /// Applies a watermark to the images of an album
 /// </summary>
 /// <param name="w">The id for a specific watermark</param>
 /// <returns></returns>
 public bool ApplyWatermark(Watermark w)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], AlbumID [required], WatermarkID [required], Callback, Pretty, Strict
     var resp = ch.ExecuteMethod<SmugMugResponse>("smugmug.albums.applyWatermark", basic, "AlbumID", id, "WatermarkID", w.id);
     if (resp.stat == "ok")
         return true;
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #45
0
 /// <summary>
 /// Add a comment to an album
 /// </summary>
 /// <param name="Text">The text for the comment</param>
 /// <param name="Rating">The rating for this comment. Values:  0 - No Rating (Default), 1 - 1 Star Rating, 2 - 2 Star Rating, 3 - 3 Star Rating, 4 - 4 Star Rating, 5 - 5 Star Rating</param>
 /// <param name="Extras">A comma separated string of additional attributes to return in the response</param>
 /// <returns></returns>
 public Comment AddComment(string Text, int Rating, string Extras)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], AlbumID [required], AlbumKey [required], Text [required], Callback, Extras, Pretty, Rating, Strict
     var resp = ch.ExecuteMethod<CommentResponse>("smugmug.albums.comments.add", basic, "AlbumID", id, "AlbumKey", Key, "Text", Text, "Rating", Rating, "Extras", Extras);
     if (resp.stat == "ok")
     {
         var myComment = resp.Comment;
         if (myComment != null)
         {
             if (string.IsNullOrEmpty(myComment.Text))
                 myComment.Text = Text;
             if (myComment.Rating == 0)
                 myComment.Rating = Rating;
             //Hack: The class has 2 properties with the same name - Comments. I've separated them in 2 different properties (HasComments and CommentsList)
             if (this.CommentsList == null)
                 this.CommentsList = new List<Comment>();
             this.CommentsList.Add(myComment);
         }
         return myComment;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #46
0
 /// <summary>
 /// Creates a new album with the specified parameters - Title [required], AlbumTemplateID, Backprinting (pro only), BoutiquePackaging (pro only), CanRank, CategoryID, Clean, ColorCorrection, Comments, CommunityID, DefaultColor (pro only), Description, EXIF, External, FamilyEdit, FriendEdit, Geography, Header (power&pro only), HideOwner, InterceptShipping, Keywords, Larges (pro only), Originals, PackagingBranding (pro only), Password, PasswordHint, Position, Printable, PrintMarkID (pro only), ProofDays (pro only), Protected (power&pro only), Public, Share, SmumugSearchable, SortDirection, SortMethod, SquareThumbs, SubCategoryID, TemplateID, ThemeID, Unique, UnsharpAmount (power&pro only), UnsharpRadius (power&pro only), UnsharpSigma (power&pro only), UnsharpThreshold (power&pro only), WatermarkID (pro only), Watermarking (pro only), WorldSearchable, X2Larges, X3Larges, XLarges (pro only)
 /// </summary>
 /// <param name="Unique">Create an album if one of the same name doesn't already exist in the current hierarchy. Default: false.</param>
 /// <param name="Extras">A comma seperated string of additional attributes to return in the response.</param>
 /// <returns>Album (id and Key)</returns>
 internal Album Create(bool Unique, string Extras)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], Title [required], Callback, Pretty, Strict, AlbumTemplateID, Backprinting (pro only), BoutiquePackaging (pro only), CanRank,
     // CategoryID, Clean, ColorCorrection, Comments, CommunityID, DefaultColor (pro only), Description, EXIF, External, FamilyEdit, FriendEdit,
     // Geography, Header (power&pro only), HideOwner, InterceptShipping, Keywords, Larges (pro only), Originals, PackagingBranding (pro only), Password,
     // PasswordHint, Position, Printable, PrintMarkID (pro only), ProofDays (pro only), Protected (power&pro only), Public, Share, SmumugSearchable,
     // SortDirection, SortMethod, SquareThumbs, SubCategoryID, TemplateID, ThemeID, Unique, UnsharpAmount (power&pro only), UnsharpRadius (power&pro only),
     // UnsharpSigma (power&pro only), UnsharpThreshold (power&pro only), WatermarkID (pro only), Watermarking (pro only), WorldSearchable,
     // X2Larges, X3Larges, XLarges (pro only)
     this.Unique = Unique;
     // Hack: The class has 2 properties with the same name - Comments. I've separated them in 2 different properties (HasComments and CommentsList)
     var ls = BuildPropertiesValueList(this,"Category", "SubCategory", "HasComments", "CommentsList","Comments");
     ls.Add("Comments"); ls.Add("false");
     ls.Add("Extras"); ls.Add(Extras);
     if (this.Category != null)
     {
         ls.Add("CategoryID"); ls.Add(this.Category.id.ToString());
     }
     if (this.SubCategory != null)
     {
         ls.Add("SubCategoryID"); ls.Add(this.SubCategory.id.ToString());
     }
     var resp = ch.ExecuteMethod<AlbumResponse>("smugmug.albums.create", basic, ls.ToArray());
     if (resp.stat == "ok")
     {
         var temp = resp.Album;
         temp.basic = basic;
         temp.Title = this.Title;
         if (this.SubCategory != null)
         {
             temp.SubCategory = this.SubCategory;
             temp.Category = this.Category;
             if (this.SubCategory.Albums == null)
                 this.SubCategory.Albums = new List<Album>();
             this.SubCategory.Albums.Add(temp);
         }
         else
         {
             if (this.Category != null)
             {
                 temp.Category = this.Category;
                 if (this.Category.Albums == null)
                     this.Category.Albums = new List<Album>();
                 this.Category.Albums.Add(temp);
             }
         }
         return temp;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #47
0
 /// <summary>
 /// Uploads an image from a URL to an album - Image with id, Key and URL
 /// </summary>
 /// <param name="URL">The URL for the image</param>
 /// <param name="Altitude">The altitude at which the image (or video) was taken</param>
 /// <param name="ByteCount">The size of the image (or video) in bytes</param>
 /// <param name="Caption">The caption for the image (or video)</param>
 /// <param name="Filename">The filename of the image (or video)</param>
 /// <param name="Keywords">The keyword string for the image (or video)</param>
 /// <param name="Latitude">The latitude at which the image (or video) was taken</param>
 /// <param name="Longitude">The longitude at which the image (or video) was taken</param>
 /// <param name="MD5Sum">The MD5 sum for the image (or video)</param>
 /// <param name="Extras">A comma seperated string of additional attributes to return in the response.</param>
 /// <returns>Image (id, Key, URL)</returns>
 public Image UploadImageFromURL(string URL, int Altitude, int ByteCount, string Caption, string Filename, string Keywords, float Latitude, float Longitude, string MD5Sum, string Extras)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], AlbumID [required], URL [required], Altitude, ByteCount, Caption, Filename, Keywords, Latitude, Longitude, MD5Sum, Callback, Pretty, Strict
     var resp = ch.ExecuteMethod<ImageResponse>("smugmug.images.uploadFromURL", basic, "AlbumID", id, "URL", URL, "Altitude", Altitude, "ByteCount", ByteCount, "Caption", Caption, "Filename", Filename, "Keywords", Keywords, "Latitude", Latitude, "Longitude", Longitude, "MD5Sum", MD5Sum, "Extras", Extras);
     if (resp.stat == "ok")
     {
         var temp = new Image();
         temp.basic = basic;
         return temp;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #48
0
 /// <summary>
 /// Retrieve the user's list of printmarks.
 /// </summary>
 /// <param name="Heavy">Returns a heavy response for this method. Default: false.</param>
 /// <param name="Extras">A comma separated string of additional attributes to return in the response.</param>
 /// <returns>List of printmarks</returns>
 public List<Printmark> GetPrintmarks(bool Heavy, string Extras)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], Associative, Callback, Extras, Heavy, Pretty, Strict
     var resp = ch.ExecuteMethod<PrintmarkResponse>("smugmug.printmarks.get", basic, "Heavy", Heavy, "Extras", Extras);
     if (resp.stat == "ok")
     {
         List<Printmark> printmarkList = new List<Printmark>();
         printmarkList.AddRange(resp.Printmarks);
         if (printmarkList != null)
         {
             foreach (var myPrintmark in printmarkList)
             {
                 myPrintmark.basic = basic;
             }
         }
         return printmarkList;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #49
0
 /// <summary>
 /// Updates specific settings (Dissolve, ImageID, Location, Name) for a the current sharegroup. If any of the parameters are missing or are empty strings "", they're ignored and the current settings are preserved. Otherwise, they're updated with the new settings.
 /// </summary>
 /// <param name="AccessPassworded">Allow access to password protected albums from the sharegroup without the password. Default: false.</param>
 /// <param name="Description">The description for the sharegroup</param>
 /// <param name="Name">The name for the sharegroup</param>
 /// <param name="Password">The password for the sharegroup</param>
 /// <param name="PasswordHint">The password hint for the sharegroup</param>
 /// <param name="Extras">A comma separated string of additional attributes to return in the response</param>
 /// <returns>Returns an empty successful response, if it completes without error</returns>
 public async Task<bool> ModifyAsync(bool AccessPassworded, string Description, string Name, string Password, string PasswordHint, string Extras)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], ShareGroupID [required], AccessPassworded, Callback, Description, Extras, Name, Password, PasswordHint, Pretty, Strict
     var resp = await ch.ExecuteMethod<SmugMugResponse>("smugmug.sharegroups.modify", basic, "AccessPassworded", AccessPassworded, "Description", Description, "Extras", Extras, "Name", Name, "Password", Password, "PasswordHint", PasswordHint);
     if (resp.stat == "ok")
         return true;
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #50
0
 /// <summary>
 /// Update on SmugMug a printmark modified locally (Dissolve, ImageID, Location, Name). If any of the parameters are missing or are empty strings "", they're ignored and the current settings are preserved. Otherwise, they're updated with the new settings.
 /// </summary>
 /// <param name="Extras">A comma separated string of additional attributes to return in the response.</param>
 /// <returns></returns>
 public bool Modify(string Extras)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], PrintmarkID [required], Callback, Dissolve, Extras, ImageID, Location, Name, Pretty, Strict
     var ls = BuildPropertiesValueList(this, "id", "Image");
     ls.Add("PrintmarkID"); ls.Add(this.id.ToString());
     ls.Add("ImageID"); ls.Add(this.Image.id.ToString());
     ls.Add("Extras"); ls.Add(Extras);
     var resp = ch.ExecuteMethod<SmugMugResponse>("smugmug.printmarks.modify", basic, ls.ToArray());
     if (resp.stat == "ok")
         return true;
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #51
0
 /// <summary>
 /// Pings SmugMug
 /// </summary>
 /// <returns>Returns an empty successful response, if it completes without error.</returns>
 public async Task<bool> PingAsync()
 {
     // APIKey [required], Callback, Pretty
     CommunicationHelper ch = new CommunicationHelper();
     var resp = await ch.ExecuteMethod<SmugMugResponse>("smugmug.service.ping", null);
     if (resp.stat == "ok")
         return true;
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #52
0
 /// <summary>
 /// Updates specific settings (Dissolve, ImageID, Location, Name) for the current printmark. If any of the parameters are missing or are empty strings "", they're ignored and the current settings are preserved. Otherwise, they're updated with the new settings.
 /// </summary>
 /// <param name="Name">The name for the printmark</param>
 /// <param name="Location">The location of the printmark on the target image. Values: TopLeft, TopRight, BottomLeft, BottomRight, Top, Bottom</param>
 /// <param name="Dissolve">The opacity of the printmark on the target image. Min: 0. Max: 100</param>
 /// <param name="ImageID">The id for a specific image</param>
 /// <param name="Extras">A comma separated string of additional attributes to return in the response.</param>
 /// <returns>Returns an empty successful response, if it completes without error</returns>
 public bool Modify(string Dissolve, string ImageID, string Location, string Name, string Extras)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], PrintmarkID [required], Callback, Dissolve, Extras, ImageID, Location, Name, Pretty, Strict
     var resp = ch.ExecuteMethod<SmugMugResponse>("smugmug.printmarks.modify", basic, "PrintmarkID", this.id, "Dissolve", Dissolve, "Extras", Extras, "ImageID", ImageID, "Location", Location, "Name", Name);
     if (resp.stat == "ok")
         return true;
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #53
0
 /// <summary>
 /// Retrieves a list of style templates
 /// </summary>
 /// <param name="Associative">Returns an associative array. Default: false </param>
 /// <returns>List of Templates (id and Name)</returns>
 public async Task<List<Template>> StylesGetTemplatesAsync(bool Associative)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // Associative, Callback, Pretty, Strict
     var resp = await ch.ExecuteMethod<TemplateResponse>("smugmug.styles.getTemplates", null, "Associative", Associative);
     if (resp.stat == "ok")
     {
         var temp = new List<Template>();
         temp.AddRange(resp.Templates);
         return temp;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #54
0
 /// <summary>
 /// Populate the current printmark with info from the site  (id, Name, Dissolve, Image struct - id, key; Location)
 /// </summary>
 /// <returns></returns>
 public void PopulatePrintmarkWithInfoFromSite()
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], PrintmarkID [required], Callback, Pretty, Strict
     var resp = ch.ExecuteMethod<PrintmarkResponse>("smugmug.printmarks.getInfo", basic, "PrintmarkID", id);
     if (resp.stat == "ok")
         PopulateWithResponse(resp.Printmark, this);
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #55
0
 /// <summary>
 /// Populate the current sharegroup with info from the site  (id, Tag, AccessPassworded, AlbumCount, Albums array - id, key, Title; Description, Name, Password, PasswordHint, Passworded, URL)
 /// </summary>        
 /// <param name="Password">The password for the sharegroup</param>
 /// <param name="ShareGroupTag">The tag (public id) for the sharegroup</param>
 /// <param name="Extras">A comma separated string of additional attributes to return in the response</param>
 public async Task PopulateShareGroupWithInfoFromSiteAsync(string Password, string Extras)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], ShareGroupID [required], Callback, Extras, Password, Pretty, SharegroupTag, Strict
     var resp = await ch.ExecuteMethod<ShareGroupResponse>("smugmug.sharegroups.getInfo", basic, "ShareGroupID", id, "Password", Password, "ShareGroupTag", this.Tag, "Extras", Extras);
     if (resp.stat == "ok")
         PopulateWithResponse(resp.ShareGroup, this);
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #56
0
 /// <summary>
 /// Removes an album from a specified sharegroup 
 /// </summary>
 /// <param name="AlbumToRemove">Album to be removed from the sharegroup</param>
 /// <returns></returns>
 public async Task<bool> RemoveAlbumAsync(Album AlbumToRemove)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], ShareGroupID [required], AlbumID [required], Callback, Pretty, Strict 
     var resp = await ch.ExecuteMethod<SmugMugResponse>("smugmug.sharegroups.albums.remove", basic, "ShareGroupID", id, "AlbumID", AlbumToRemove.id);
     if (resp.stat == "ok")
     {
         if (this.Albums != null)
         {
             // Remove the album from this sharegroup
             this.Albums.Remove(AlbumToRemove);
             // Decrease the no of albums this sharegroup has
             this.AlbumCount--;
         }
         return true;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #57
0
        /// <summary>
        /// Retrieves a list of images for a given album (Album with id, Key, ImageCount, and Image array with id, Key, Altitude, Caption, Date, FileName, Duration, Format, Heaight, Hidden, Keywords, LargeURL, LastUpdated, Latitude, Longitude, MD5Sum, MediumURL, OriginalURL, Position, Serial, Size, SmallURL, ThumbURL, TinyURL, Video320URL, Video640URL, Video960URL, Video1280URL, Video1920URL, Width, X2LardeURL, X3LargeURL, XLargeURL)
        /// </summary>
        /// <param name="Associative">boolean, returns an associative array. Default: false</param>
        /// <param name="Extras">A comma seperated string of additional attributes to return in the response.</param>
        /// <param name="Heavy">heavy response. Default : false</param>
        /// <param name="LastUpdated">Return results where LastUpdated is after the epoch time provided</param>
        /// <param name="Sandboxed">Forces URLs to a location with a crossdomain.xml file. Default: false  </param>
        /// <param name="SitePassword">The site password for a specific user</param>
        /// <returns>List of Images</returns>
        public List<Image> GetImages(bool Associative, string Extras, bool Heavy, int LastUpdated, bool Sandboxed, string SitePassword)
        {
            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();
            _logger.Debug("Getting images from smugmug with heave={0}", Header);
            CommunicationHelper ch = new CommunicationHelper();
            // SessionID [required], AlbumID [required], AlbumKey [required], Callback, Extras, Heavy, LastUpdated, Password, Pretty, Sandboxed (boolean. Forces URLs to a location with a crossdomain.xml file. Default: false), SitePassword, Strict
            ImageResponse resp = new ImageResponse();
            if ((Password != null) && (Password != String.Empty))
                resp = ch.ExecuteMethod<ImageResponse>("smugmug.images.get", basic, "AlbumID", id, "AlbumKey", Key, "Associative", Associative, "Extras", Extras, "Heavy", Heavy, "LastUpdated", LastUpdated, "Sandboxed", Sandboxed,"SitePassword", SitePassword, "Password", Password);
            else
                resp = ch.ExecuteMethod<ImageResponse>("smugmug.images.get", basic, "AlbumID", id, "AlbumKey", Key, "Associative", Associative, "Extras", Extras, "Heavy", Heavy, "LastUpdated", LastUpdated, "Sandboxed", Sandboxed,"SitePassword", SitePassword);

               			_logger.Debug("Finished getting images from smugmug in {0:n} milliseconds.", stopWatch.ElapsedMilliseconds);
            stopWatch.Stop();
            if (resp.stat == "ok")
            {
                _logger.Debug("Smugmug images.get response was ok.");

                var imageList = new List<Image>();
                imageList.AddRange(resp.Album.Images);
                this.ImageCount = resp.Album.ImageCount;
                if (imageList != null)
                {
                    foreach (var item in imageList)
                    {
                        item.basic = basic;
                        item.Album = this;
                    }
                }
                return imageList;
            }
            else
            {
                Console.WriteLine(resp.message);
                throw new SmugMugException(resp.code, resp.message, resp.method);
            }
        }
Beispiel #58
0
 /// <summary>
 /// Populate the current album and its images with transfer statistics during the given Month and Year (id, Key, Bytes, Hits, Large, Medium, original, Small, Thumb, Tiny, X2Large, X3Large, XLarge, Video320, Video640, Video960, Video1280, Video1960). SmugMug only keeps the last few months of traffic on file, so requesting farther back then 2 months may not return valid results. A float is provided for Original and video sizes because it's possible to watch only a portion of a video
 /// </summary>
 /// <param name="Month"></param>
 /// <param name="Year"></param>
 /// <param name="Heavy">If Heavy is set to "1", transfer statistics for each image in each album will be returned as well</param>
 /// <returns></returns>
 public void PopulateAlbumWithStatsFromSite(int Month, int Year, bool Heavy)
 {
     CommunicationHelper ch = new CommunicationHelper();
     var resp = ch.ExecuteMethod<AlbumResponse>("smugmug.albums.getStats", basic, "AlbumID", id, "Month", Month, "Year", Year, "Heavy", Heavy);
     if (resp.stat == "ok")
     {
         PopulateWithResponse(resp.Album, this, "HasComments", "CommentsList", "Comments");
         //Hack: The class has 2 properties with the same name - Comments. I've separated them in 2 different properties (HasComments and CommentsList)
         if (resp.Album.Comments != null)
             this.HasComments = (bool)resp.Album.Comments;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }
Beispiel #59
0
        /// <summary>
        /// Retrieves a list of albums for a sharegroup (also populates the current sharegroup with this list)
        /// </summary>
        /// <param name="Associative">Returns an associative array. Default: false.</param>
        /// <param name="Password">The password for the sharegroup</param>
        /// <param name="Extras">A comma separated string of additional attributes to return in the response</param>
        /// <returns></returns>
        public async Task<List<Album>> GetAlbumsAsync(bool Associative, string Password, string Extras)
        {
            CommunicationHelper ch = new CommunicationHelper();
            // SessionID [required], ShareGroupTag [required], Associative, Callback, Extras, Password, Pretty, Strict
            var resp = await ch.ExecuteMethod<ShareGroupResponse>("smugmug.sharegroups.albums.get", basic, "ShareGroupTag", Tag, "Associative", Associative, "Password", Password, "Extras", Extras);
            if (resp.stat == "ok")
            {
                var shareGroupAlbums = resp.ShareGroup.Albums;
                if (shareGroupAlbums != null)
                {
                    foreach (var item in shareGroupAlbums)
                    {
                        bool flag = true;
                        item.basic = basic;
                        foreach (var myAlbum in this.Albums)
                        {
                            if (item.id == myAlbum.id)
                            {
                                flag = false;
                                break;
                            }
                        }
                        // Populate the current sharegroup with its albums from the site
                        if (flag)
                        {
                            if (this.Albums == null)
                                this.Albums = new List<Album>();
                            this.Albums.AddRange(shareGroupAlbums);
                        }
                    }
                    this.AlbumCount = shareGroupAlbums.Count;
                }

                return shareGroupAlbums;
            }
            else
            {
                Console.WriteLine(resp.message);
                throw new SmugMugException(resp.code, resp.message, resp.method);
            }
        } 
Beispiel #60
0
 /// <summary>
 /// Retrieves the details for a specified album (id, Key, Backprinting, CanRank, CategoryID and Name, Clean, ColorCorrection, Comments, CommunityID and Name, Description, EXIF, External, FamilyEdit, FriendEdit, Geography, Header, HideOwner, HighlightID and Key, ImageCount, Larges, LastUpdated, NiceName, Originals, Password, PasswordHint, Position, Printable, ProofDays, Protected, Public, Share, SmumugSearchable, SortDirection, SortMethod, SquareThumbs, SubCategoryID and Name, TemplateID, ThemeID and Name and Type, Title, Unique, UnsharpAmount, UnsharpRadius, UnsharpSigma, UnsharpThreshold, WatermarkID and Name, Watermarking, WorldSearchable, X2Larges, X3Larges, XLarges)
 /// </summary>
 /// <param name="SitePassword">The site password for a specific user</param>
 /// <returns></returns>
 public Album GetInfo(string SitePassword)
 {
     CommunicationHelper ch = new CommunicationHelper();
     // SessionID [required], AlbumID [required], AlbumKey [required], Callback, Password, Pretty, Sandboxed, SitePassword, Strict
     AlbumResponse resp = new AlbumResponse();
     if (!String.IsNullOrEmpty(this.Password))
         resp = ch.ExecuteMethod<AlbumResponse>("smugmug.albums.getInfo", basic, "AlbumID", id, "AlbumKey", Key, "SitePassword", SitePassword, "Password", Password);
     else
         resp = ch.ExecuteMethod<AlbumResponse>("smugmug.albums.getInfo", basic, "AlbumID", id, "AlbumKey", Key, "SitePassword", SitePassword);
     if (resp.stat == "ok")
     {
         var myAlbum= resp.Album;
         myAlbum.basic = basic;
         //Hack: The class has 2 properties with the same name - Comments. I've separated them in 2 different properties (HasComments and CommentsList)
         if (myAlbum.Comments != null)
             myAlbum.HasComments = (bool)myAlbum.Comments;
         return myAlbum;
     }
     else
     {
         Console.WriteLine(resp.message);
         throw new SmugMugException(resp.code, resp.message, resp.method);
     }
 }