コード例 #1
0
        /// <summary> </summary>
        JsonResult IDriver.Extract(string target, IEnumerable <string> targets)
        {
            FullPath dest     = ParsePath(target);
            var      response = new AddResponse();

            //this should move all files to a temp folder
            //then extract then there
            //then count them and get a list of the names
            //move them all in mass to the target folder
            //then respond with the file info


            foreach (var item in targets)
            {
                FullPath fullPath = ParsePath(item);

                FileInfo fileinfo = new FileInfo(fullPath.File.Name);


                DirectoryInfo newDir = Directory.CreateDirectory(file_info.site_cache_path() + "/temp/");
                file_handler.Decompress(fileinfo);


                response.added.Add((FileDTO)DTOBase.Create(fileinfo, dest.Root));
            }

            return(Json(response));
        }
コード例 #2
0
        /// <summary>
        /// Creates an AddResponse packet.
        /// </summary>
        /// <param name="context">The user context which contains message ID.</param>
        /// <param name="resultCode">Result code of previous request, as specified in RFC 2251.</param>
        /// <param name="matchedDn">Matched DN.</param>
        /// <param name="errorMessage">Error message for result code. Required.</param>
        /// <param name="referral">Referral. Optional. Used for LDAP v3 only.</param>
        /// <returns>The packet that contains the response.</returns>
        internal override AdtsAddResponsePacket CreateAddResponse(
            AdtsLdapContext context,
            MsLdap.ResultCode resultCode,
            string matchedDn,
            string errorMessage,
            string[] referral)
        {
            AddResponse addResponse = new AddResponse(
                new LDAPResult_resultCode((long)resultCode),
                new LDAPDN(matchedDn ?? string.Empty),
                new LDAPString(errorMessage ?? string.Empty),
                CreateReferral(referral));

            LDAPMessage_protocolOp operation = new LDAPMessage_protocolOp();

            operation.SetData(LDAPMessage_protocolOp.addResponse, addResponse);

            LDAPMessage           message = new LDAPMessage(new MessageID(context.MessageId), operation, null);
            AdtsAddResponsePacket packet  = new AdtsAddResponsePacket();

            packet.ldapMessagev3 = message;
            packet.messageId     = context.MessageId;

            return(packet);
        }
コード例 #3
0
        public IHttpActionResult Add([FromBody] AddRequest objAddRequest)
        {
            AddResponse objAddResponse;

            if (null != objAddRequest && ModelState.IsValid)
            {
                ContactInfoLogic objContactInfoLogic = new ContactInfoLogic();
                objAddResponse = objContactInfoLogic.Add(objAddRequest);

                //return Ok(objAddResponse);
            }
            else
            {
                //return BadRequest(ModelState);

                string strErrorMsg = string.Empty;
                foreach (var item in ModelState.Values)
                {
                    strErrorMsg += string.Join(",", item.Errors.Select(e => e.ErrorMessage));
                }
                objAddResponse = new AddResponse()
                {
                    Result = string.IsNullOrWhiteSpace(strErrorMsg) ? "Request Format Error" : strErrorMsg
                };
            }

            //轉換JSON格式回傳
            HttpResponseMessage result = new HttpResponseMessage {
                Content = new StringContent(Utility.GetJSON(objAddResponse), Encoding.GetEncoding("UTF-8"), "application/json")
            };

            return(ResponseMessage(result));
        }
コード例 #4
0
        public string Add(AddRequest petition)
        {
            AddResponse result = new AddResponse();

            logger.Debug("------- Add Method -------");

            try
            {
                if (petition == null || petition.Added == null)
                {
                    return(Error400().ErrorMessage.ToString());
                }

                string key = Request.Headers.GetValues("X_Evi_Tracking_Id").FirstOrDefault();
                JournalService.Storing(Operations.Add(petition, result), "Sum", key);

                logger.Debug(Operations.Add(petition, result));

                var hasonServer = JsonConvert.SerializeObject(result);
                return(hasonServer);
            }
            catch (Exception ex)
            {
                return(JsonConvert.SerializeObject(Error500(ex)));
            }
        }
コード例 #5
0
ファイル: LDAP.cs プロジェクト: trungpv/Galactic
        /// <summary>
        /// Adds an entry to the LDAP directory with the specified distinguished name and attributes.
        /// </summary>
        /// <param name="dn">The distinguished name of the entry to add.</param>
        /// <param name="attributes">The attributes for the entry to add.</param>
        /// <returns>True if added, false otherwise.</returns>
        public bool Add(string dn, DirectoryAttribute[] attributes)
        {
            if (!string.IsNullOrWhiteSpace(dn))
            {
                AddRequest request = new AddRequest(dn, attributes);
                try
                {
                    AddResponse response = (AddResponse)connection.SendRequest(request);

                    // Check that a response was received.
                    if (response != null)
                    {
                        // A response was received.
                        if (response.ResultCode == ResultCode.Success)
                        {
                            return(true);
                        }
                    }
                    else
                    {
                        // A response was not received.
                        return(false);
                    }
                }
                catch
                {
                }
            }
            return(false);
        }
コード例 #6
0
        public void CreateComment_WcfThrowsFaultExceptionValidationFault_ThrowsServiceValidationException()
        {
            //Arrange
            long JobSeekerID = 12345678;
            var  comment     = new CommentModel {
                CommentID = JobSeekerID, Text = "This is fun creating a testing generic Comment", Topic = "APP"
            };
            var inModel = new JobseekerModel {
                CurrentComment = comment
            };
            var request   = MappingEngine.Map <AddRequest>(inModel);
            var response  = new AddResponse();
            var exception = new FaultException <ValidationFault>(new ValidationFault {
                Details = new List <ValidationDetail> {
                    new ValidationDetail {
                        Key = "Key", Message = "Message"
                    }
                }
            });

            mockMappingEngine.Setup(m => m.Map <AddRequest>(inModel)).Returns(request);
            mockCommentWcf.Setup(m => m.Add(request)).Throws(exception);

            //Act
            SystemUnderTest().CreateComment(inModel);
        }
コード例 #7
0
ファイル: TagRepository.cs プロジェクト: sergkl/ExpenseSystem
        /// <summary>
        /// Add tag to database
        /// </summary>
        /// <param name="userId">User identifier</param>
        /// <param name="name">Caption for new tag</param>
        /// <param name="parentId">Parent identifier for tag</param>
        /// <returns>Execution result with identifier for new tag</returns>
        public AddResponse Add(int userId, string name, int parentId)
        {
            var addResponse = new AddResponse();
            if (HasUserAccess(userId, parentId))
            {
                if (string.IsNullOrEmpty(name))
                {
                    addResponse.IsError = true;
                    addResponse.Errors.Add(Error.TagNameHasNotBeenSet);
                }
                else
                {
                    var tag = new Tag();
                    tag.Parent = GetById(userId, parentId).Object;
                    tag.Name = name;
                    tag.User = new UserRepository(context).GetById(userId, userId).Object;
                    context.Tags.AddObject(tag);
                    context.Save();
                    addResponse.Id = tag.Id;
                }
            }
            else
            {
                addResponse.IsError = true;
                addResponse.Errors.Add(Error.UserDoesNotHaveAccess);
            }

            return addResponse;
        }
コード例 #8
0
ファイル: Client.cs プロジェクト: sasanchez7/calculatorv3
        public static void AdditionPetition(AddRequest calc, int id)
        {
            try
            {
                var httpWebRequest = HeaderBuilder("Calculator", "add", id);

                string json = JsonConvert.SerializeObject(calc);

                SendRequest(httpWebRequest, json);

                AddResponse     response     = null;
                HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                    response = JsonConvert.DeserializeObject <AddResponse>(result);
                }

                Console.WriteLine("Sum: " + response.Sum + "\n\npress enter to continue.");
                Console.ReadKey();
            }
            catch (WebException webex)
            {
                WebResponse errResp = webex.Response;
                using (Stream respStream = errResp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream);
                    string       text   = reader.ReadToEnd();
                    Console.WriteLine(text);
                }
            }
        }
コード例 #9
0
ファイル: Test.cs プロジェクト: tubthoj89/Personal-Projects
        public void ResponseAdd(int orderNumber, bool expectedResult)
        {
            Orders order = new Orders()
            {
                dateTime               = new DateTime(2020, 06, 06),
                OrderNumber            = orderNumber,
                CustomerName           = "Wise",
                State                  = "OH",
                TaxRate                = 6.25m,
                ProductType            = "Wood",
                Area                   = 100.00m,
                CostPerSquareFoot      = 5.15m,
                LaborCostPerSquareFoot = 4.75m
            };

            if (order.OrderNumber != orderNumber)
            {
                AddResponse response = manager.AddOrder(new DateTime(2020, 06, 06), order);
                Assert.AreEqual(expectedResult, response.Success);

                if (response.Success == true)
                {
                    repo.DeleteOrder(order);
                }
            }
        }
コード例 #10
0
        public void AddDn(LdapObj ldapObj)
        {
            List <DirectoryAttribute> dirAttribs = new List <DirectoryAttribute>();

            foreach (KeyValuePair <String, LdapAttribut> ldapAttribut in ldapObj.ldapAttributs)
            {
                if (ldapAttribut.Value.values.Count > 0)
                {
                    foreach (Byte[] tb in ldapAttribut.Value.values)
                    {
                        Console.WriteLine(ldapAttribut.Key + " <=> " + Encoding.UTF8.GetString(tb));
                    }
                    dirAttribs.Add(new DirectoryAttribute(ldapAttribut.Key, ldapAttribut.Value.values.ToArray()));
                }
            }

            // create an addrequest object
            AddRequest addRequest = new AddRequest(ldapObj.dn, dirAttribs.ToArray());

            Connect2();
            try
            {
                AddResponse addreponse = ldapConnexion.SendRequest(addRequest) as AddResponse;
            }
            catch (DirectoryOperationException e)
            {
                Console.WriteLine(e.Message);
                throw e;
            }
        }
コード例 #11
0
            //public bool EntryExists(string login)
            //{
            //    bool exits = true;
            //    try
            //    {
            //        string ldapSearchFilter = "cn=" + login.Trim();
            //        message += ldapSearchFilter;
            //        SearchRequest searchRequest = new SearchRequest
            //                                        ("",
            //                                          ldapSearchFilter,
            //                                          System.DirectoryServices.Protocols.SearchScope.Subtree,
            //                                          null);
            //        SearchResponse searchResponse =
            //                    (SearchResponse)Connection.SendRequest(searchRequest);

            //        message += String.Format("\r\nSearch Response Entries:{0}",
            //                    searchResponse.Entries.Count);
            //        if (searchResponse.Entries.Count > 0)
            //        {
            //            exits = true;
            //        }
            //        else
            //        {
            //            exits = false;
            //        }
            //    }
            //    catch (Exception e)
            //    {
            //        message += String.Format("\nUnexpected exception occured:\n\t{0}: {1}",
            //                          e.GetType().Name, e.Message);
            //        exits = false;
            //    }
            //    return exits;
            //}



            public string CreateEntry(INovellOrganizationContactPerson person)
            {
                // LdapAttributeSet attributeSet = new LdapAttributeSet();
                // attributeSet.Add(new LdapAttribute(
                //                     "objectclass", "inetOrgPerson"));
                ///attributeSet.Add(new LdapAttribute("cn",
                // new string[] { person.Login }));

                //attributeSet.Add(new LdapAttribute("givenname",
                //                     person.FirstName));
                //attributeSet.Add(new LdapAttribute("sn", person.Surname));
                //attributeSet.Add(new LdapAttribute("mail", person.Email));
                //attributeSet.Add(new LdapAttribute("userpassword", person.Password));
                // string dn = "cn=" + person.Login + ",ou=Users,o=Alien";
                //LdapEntry newEntry = new LdapEntry(dn, attributeSet);
                //Connection.Add(newEntry);
                //return newEntry.DN;


                string containerName = "ou=Users,o=Alien";
                // string login = "******";

                string     dn           = "cn=" + person.Login + "," + containerName;
                string     dirClassType = "inetOrgPerson";
                AddRequest addRequest   = new AddRequest(dn, dirClassType);

                addRequest.Attributes.Add(new DirectoryAttribute("cn", new string[] { person.Login }));
                addRequest.Attributes.Add(new DirectoryAttribute("givenname", person.FirstName));
                addRequest.Attributes.Add(new DirectoryAttribute("sn", person.Surname));
                addRequest.Attributes.Add(new DirectoryAttribute("mail", person.Email));
                addRequest.Attributes.Add(new DirectoryAttribute("userpassword", person.Password));
                AddResponse addResponse = (AddResponse)connection.SendRequest(addRequest);

                return(dn);
            }
コード例 #12
0
 /// <summary>
 /// Add new entity to database
 /// </summary>
 /// <param name="userId">User Identifier</param>
 /// <param name="entity">Entity</param>
 /// <returns>Entity identifier</returns>
 public AddResponse Add(int userId, User entity)
 {
     var addResponse = new AddResponse();
     if (entity == null)
     {
         addResponse.IsError = true;
         addResponse.Id = 0;
         addResponse.Errors.Add(Error.UserObjectCantBeNull);
     }
     else if (string.IsNullOrEmpty(entity.Login) ||
              string.IsNullOrEmpty(entity.Password) ||
              string.IsNullOrEmpty(entity.FirstName) ||
              string.IsNullOrEmpty(entity.LastName) ||
              string.IsNullOrEmpty(entity.Email))
     {
         addResponse.IsError = true;
         addResponse.Id = 0;
         addResponse.Errors.Add(Error.UserProvidedNotFullNeededInformation);
     }
     else
     {
         context.Users.AddObject(entity);
         context.Save();
         addResponse.Id = entity.Id;
     }
     return addResponse;
 }
コード例 #13
0
ファイル: Calculator.cs プロジェクト: germangc125/Calculator
        public static void Add(AddRequest numbers, string EviTrackingID)
        {
            var client  = new RestClient(urlBase);
            var request = new RestRequest("Add", Method.POST);

            if (EviTrackingID != "")
            {
                request.AddHeader("x-evi-tracking-id", EviTrackingID);
            }
            else if (EviTrackingID == "")
            {
                request.AddHeader("x-evi-tracking-id", "0");
            }
            //var filters = "{\"Addends\":\"" + numbers.Split(' ')[0] + "\"}";
            request.AddParameter("application/json", new JavaScriptSerializer().Serialize(numbers), ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);

            Console.WriteLine();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                AddResponse result = (new JavaScriptSerializer()).Deserialize <AddResponse>(response.Content);
                Console.WriteLine("Resultado:" + result.Sum + ". " + (EviTrackingID != "" ? "y se guardo en el log." : ""));
            }
            else
            {
                Console.WriteLine("Ha ocurrido un error: " + response.ErrorMessage);
            }
            Console.WriteLine("Fin del programa, va a volver al menu");
            Console.WriteLine();
        }
コード例 #14
0
        public static void Insert(string parent, object contents, Action <bool, string> onFinished = null)
        {
            if (Application.Manifest == null || string.IsNullOrEmpty(Application.Manifest.DatabaseUrl))
            {
                return;
            }
            Add add = new Add()
            {
                Auth    = Application.Integration.Auth,
                Content = JsonConvert.SerializeObject(contents),
                Parent  = parent
            };
            NameValueCollection nameValueCollection = new NameValueCollection()
            {
                { "data", JsonConvert.SerializeObject(add) }
            };
            Uri       uri       = new Uri(Application.Manifest.DatabaseUrl.Replace("{action}", "add"));
            WebClient webClient = new WebClient()
            {
                Encoding = Encoding.UTF8
            };

            if (onFinished != null)
            {
                webClient.UploadValuesCompleted += new UploadValuesCompletedEventHandler((object s, UploadValuesCompletedEventArgs e) => {
                    AddResponse addResponse = JsonConvert.DeserializeObject <AddResponse>(Encoding.UTF8.GetString(e.Result));
                    onFinished(addResponse.Status == "ok", addResponse.Id);
                });
            }
            webClient.UploadValuesAsync(uri, "POST", nameValueCollection);
        }
コード例 #15
0
        JsonResult IDriver.Duplicate(IEnumerable <string> targets)
        {
            AddResponse response = new AddResponse();

            foreach (var target in targets)
            {
                FullPath fullPath = ParsePath(target);
                if (fullPath.Directory != null)
                {
                    var parentPath = fullPath.Directory.Parent.FullName;
                    var name       = fullPath.Directory.Name;
                    var newName    = string.Format(@"{0}\{1} copy", parentPath, name);
                    if (!Directory.Exists(newName))
                    {
                        DirectoryCopy(fullPath.Directory, newName, true);
                    }
                    else
                    {
                        for (int i = 1; i < 100; i++)
                        {
                            newName = string.Format(@"{0}\{1} copy {2}", parentPath, name, i);
                            if (!Directory.Exists(newName))
                            {
                                DirectoryCopy(fullPath.Directory, newName, true);
                                break;
                            }
                        }
                    }
                    response.Added.Add(DTOBase.Create(new DirectoryInfo(newName), fullPath.Root));
                }
                else
                {
                    var parentPath = fullPath.File.Directory.FullName;
                    var name       = fullPath.File.Name.Substring(0, fullPath.File.Name.Length - fullPath.File.Extension.Length);
                    var ext        = fullPath.File.Extension;

                    var newName = string.Format(@"{0}\{1} copy{2}", parentPath, name, ext);

                    if (!File.Exists(newName))
                    {
                        fullPath.File.CopyTo(newName);
                    }
                    else
                    {
                        for (int i = 1; i < 100; i++)
                        {
                            newName = string.Format(@"{0}\{1} copy {2}{3}", parentPath, name, i, ext);
                            if (!File.Exists(newName))
                            {
                                fullPath.File.CopyTo(newName);
                                break;
                            }
                        }
                    }
                    response.Added.Add(DTOBase.Create(new FileInfo(newName), fullPath.Root));
                }
            }
            return(Json(response));
        }
コード例 #16
0
        private void AddOrganizationalRole(LdapConnection connection, string entryDn)
        {
            string      dn          = entryDn + "," + LdapConfiguration.Configuration.Domain;
            AddRequest  addRequest  = new AddRequest(dn, "organizationalRole");
            AddResponse addResponse = (AddResponse)connection.SendRequest(addRequest);

            Assert.Equal(ResultCode.Success, addResponse.ResultCode);
        }
コード例 #17
0
        public static async void GetAllStudents()
        {
            SchoolServiceSoapClient proxy = new SchoolServiceSoapClient(EndpointConfiguration.SchoolServiceSoap);
            AddResponse             add   = await proxy.AddAsync(10, "Vitor");

            GetStudentsResponse get = await proxy.GetStudentsAsync();

            Console.WriteLine(get.Body.GetStudentsResult);
        }
コード例 #18
0
        public AddResponse Add(AddRequest request)
        {
            var response = new AddResponse()
            {
                Result = request.X + request.Y
            };

            _log.DebugFormat("Add, X={0}, Y={1}, Result={2}", request.X, request.Y, response.Result);
            return(response);
        }
コード例 #19
0
        public JsonResult Upload(string target, string name, byte[] fileBytes)
        {
            FullPath dest     = ParsePath(target);
            var      response = new AddResponse();

            if (dest.Root.MaxUploadSize.HasValue)
            {
                if (fileBytes.Length > dest.Root.MaxUploadSize.Value)
                {
                    return(Error.MaxUploadFileSize());
                }
            }

            FileInfo path = new FileInfo(Path.Combine(dest.Directory.FullName, name));

            if (path.Exists)
            {
                if (dest.Root.UploadOverwrite)
                {
                    //if file already exist we rename the current file,
                    //and if upload is succesfully delete temp file, in otherwise we restore old file
                    string tmpPath  = path.FullName + Guid.NewGuid();
                    bool   uploaded = false;
                    try
                    {
                        File.WriteAllBytes(tmpPath, fileBytes);
                        uploaded = true;
                    }
                    catch { }
                    finally
                    {
                        if (uploaded)
                        {
                            File.Delete(path.FullName);
                            File.Move(tmpPath, path.FullName);
                        }
                        else
                        {
                            File.Delete(tmpPath);
                        }
                    }
                }
                else
                {
                    File.WriteAllBytes(Path.Combine(path.DirectoryName, Helper.GetDuplicatedName(path)), fileBytes);
                }
            }
            else
            {
                File.WriteAllBytes(path.FullName, fileBytes);
            }
            response.Added.Add((FileDTO)DTOBase.Create(new FileInfo(path.FullName), dest.Root));

            return(Json(response));
        }
コード例 #20
0
        public void Add(string trackingId)
        {
            #region AddStuff
            Console.WriteLine("------Addition Operation------");
            Console.WriteLine("Type the integer sum you want to do(ex:13 + 12 + 5): ");

            char   symb = '+';
            string sum  = Console.ReadLine();

            sum = CheckingSymbol.HaveOperationSymbol(symb, sum);

            int[] numbers;
            if (ParsingComprobation.CanBeParsed(symb, sum))
            {
                numbers = ParsingComprobation.Parse(ParsingComprobation.SeparateString(symb, sum));
            }
            else
            {
                return;
            }
            #endregion

            #region Connection
            AddRequest  addition = new AddRequest();
            AddResponse result   = new AddResponse();

            addition.Added = numbers;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"{url}Add");
            request.Method      = "POST";
            request.ContentType = "application/json";

            if (trackingId != "")
            {
                request.Headers.Add("X_Evi_Tracking_Id", trackingId);
            }

            using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
            {
                var jason = JsonConvert.SerializeObject(addition);
                dataStream.Write(jason);
                dataStream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader stRead = new StreamReader(response.GetResponseStream()))
            {
                Console.WriteLine("The server operation's result is:");
                result = JsonConvert.DeserializeObject <AddResponse>(stRead.ReadToEnd());
                Console.WriteLine(result.Result);
                stRead.Close();
            }
            #endregion
        }
コード例 #21
0
 public AddCart(AddResponse res)
 {
     ProductsCount = res.CartCount;
     CartUid       = res.CartUid;
     Currency      = Enum.TryParse(res.Currency, out Currency result) ? result : (Currency?)null;
     Products      = new List <ICartProduct>();
     if (res.Products?.Count > 0)
     {
         Products = res.Products?.Select(p => new CartProduct(p));
     }
 }
コード例 #22
0
 public MainWindow()
 {
     InitializeComponent();
     EnvComboBox.ItemsSource   = Enum.GetValues(typeof(Environment)).Cast <Environment>();
     EnvComboBox.SelectedIndex = 0;
     RequestDelegate           = AddRequestToListBox;
     ResponseDelegate          = AddResponseToListBox;
     RequestCountDelegate      = UpdateRequestsRemainingLabel;
     PortTextBox.Text          = HttpServer.GetRandomUnusedPort().ToString();
     Server = new HttpServer();
     SubmitJobsBtn.DataContext = Server;
 }
コード例 #23
0
        public override Task <AddResponse> AddNumbers(AddRequest request, ServerCallContext context)
        {
            WriteLine($"AddNumbers request received with values {request.Value1} {request.Value2}");

            var addResponse = new AddResponse {
                Sum = (request.Value1 + request.Value2)
            };

            WriteLine($"Sending the Response {addResponse.Sum}");

            return(Task.FromResult(addResponse));
        }
コード例 #24
0
        JsonResult IDriver.Duplicate(IEnumerable <string> targets)
        {
            AddResponse response = new AddResponse();

            foreach (string target in targets)
            {
                WebDavRoot lroot = this.GetRoot(target);
                string     ext = "", path = "", nameWithoutExt = "";
                string     targetDecrypted = this.DecodeTarget(this.GetCorectTarget(target));
                DirInfo    targetInfo      = client.GetInfo(targetDecrypted);
                if (targetInfo == null)
                {
                    throw new ElFinderFileNotExists();
                }
                string destinationFileName;
                if (targetInfo.IsDirectory && targetDecrypted.EndsWith("/"))
                {
                    destinationFileName = targetDecrypted.Substring(0, targetDecrypted.Length - 1) + " (1)";
                }
                else
                {
                    path                = targetDecrypted.Replace(targetInfo.DisplayName, "");
                    ext                 = Path.GetExtension(targetInfo.DisplayName);
                    nameWithoutExt      = targetInfo.DisplayName.Replace(ext, "");
                    destinationFileName = string.Format("{0}{1} (1){2}", path, nameWithoutExt, ext);
                }

                DirInfo destInfo = client.GetInfo(destinationFileName);
                int     i        = 2;
                while (destInfo != null)
                {
                    if (targetInfo.IsDirectory && targetDecrypted.EndsWith("/"))
                    {
                        destinationFileName = string.Format("{0} ({1})", targetDecrypted.Substring(0, targetDecrypted.Length - 1), i);
                    }
                    else
                    {
                        destinationFileName = string.Format("{0}{1} ({3}){2}", path, nameWithoutExt, ext, i);
                    }

                    destInfo = client.GetInfo(destinationFileName);
                    i++;
                }

                client.Copy(targetDecrypted, destinationFileName);
                destInfo = client.GetInfo(destinationFileName);
                DirInfo parent = this.GetParent(destInfo);
                response.Added.Add(DTOBase.Create(destInfo, parent, lroot));
            }

            return(Json(response));
        }
コード例 #25
0
ファイル: Mediator.cs プロジェクト: AlbertoGut/Calculator
        public void Add(string trackingId)
        {
            #region AddStuff

            Console.WriteLine("------Addition Operation------");
            Console.WriteLine("Type the sum you want to do(ex:13 + 12 + 5): ");

            char     symb = '+';
            string   sum  = Console.ReadLine();
            string[] nums = sum.Split(symb);

            int[] numbers = new int[nums.Length];
            for (int i = 0; i < nums.Length; i++)
            {
                numbers[i] = int.Parse(nums[i].Trim());
                Console.WriteLine(numbers[i]);
            }
            #endregion

            #region Connection

            AddRequest  addition = new AddRequest();
            AddResponse result   = new AddResponse();

            addition.Added = numbers;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"{url}Add");
            request.Method      = "POST";
            request.ContentType = "application/json";

            if (trackingId != "")
            {
                request.Headers.Add("X_Evi_Tracking_Id", trackingId);
            }

            using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
            {
                var jason = JsonConvert.SerializeObject(addition);
                dataStream.Write(jason);
                dataStream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader stRead = new StreamReader(response.GetResponseStream()))
            {
                Console.WriteLine("The server operation's result is:");
                result = JsonConvert.DeserializeObject <AddResponse>(stRead.ReadToEnd());
                Console.WriteLine(result.Result);
                stRead.Close();
            }
            #endregion
        }
コード例 #26
0
        public override LdapResultCompleteStatus Handle(SafeHandle handle, Native.Native.LdapResultType resType, IntPtr msg, out DirectoryResponse response)
        {
            response = default;
            switch (resType)
            {
            case LdapForNet.Native.Native.LdapResultType.LDAP_RES_ADD:
                response = new AddResponse();
                return(LdapResultCompleteStatus.Complete);

            default:
                return(LdapResultCompleteStatus.Unknown);
            }
        }
コード例 #27
0
        static void Main(string[] args)
        {
            Arithmetic proxy = new Arithmetic();

            proxy.Url = "http://localhost/server/arithmetic.asmx";
            Add add = new Add();

            add.n1 = 10;
            add.n2 = 20;
            AddResponse resp = proxy.Add(add);

            Console.WriteLine("10 + 20 = " + resp.sum);
        }
コード例 #28
0
        public void AddResponse_CorrectlyFormatsResponseForJournal()
        {
            var sum      = TestHelper.GeneratePositiveNumber();
            var expected = sum.ToString();
            var response = new AddResponse
            {
                Sum = sum
            };

            var formattedResponse = response.GetFormatedResponse();

            formattedResponse.Should().Be(expected);
        }
コード例 #29
0
        // Methods for user parameters depending selection
        #region Add
        public void Add(string Id_Tracking)
        {
            Reqadd.Addends = new int[] { };
            Console.WriteLine("------- Operation Add -------");
            Console.WriteLine("Write the operation( Ej: 1+2+3 )");
            separator = '+';
            try
            {
                Console.WriteLine("Operation:");
                op = Console.ReadLine();

                string[] numbers = op.Trim().Split(separator);
                Reqadd.Addends = numbers.Select(x => int.Parse(x)).ToArray();

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create($"{url}add");
                req.Method      = "POST";
                req.ContentType = "application/json";

                if (Id_Tracking != "")
                {
                    req.Headers.Add("X_Evi_Tracking_Id", Id_Tracking);
                }

                // Opens a stream,converts the request to Json and send it
                using (StreamWriter sw = new StreamWriter(req.GetRequestStream()))
                {
                    string jsonRequest = JsonConvert.SerializeObject(Reqadd);
                    sw.Write(jsonRequest);
                    sw.Close();
                }

                AddResponse     response = new AddResponse();
                HttpWebResponse Response = (HttpWebResponse)req.GetResponse();
                using (StreamReader sr = new StreamReader(Response.GetResponseStream(), Encoding.UTF8))
                {
                    Console.WriteLine("The server responds: ");
                    response = JsonConvert.DeserializeObject <AddResponse>(sr.ReadToEnd());
                    Console.WriteLine(response.Sum);
                    sr.Close();
                    Response.Close();
                }
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(e.Message);
                Console.ForegroundColor = ConsoleColor.Gray;
                logger.Error(e.Message);
            }
        }
コード例 #30
0
        public AddResponse Add(AddRequest objAddRequest)
        {
            AddResponse           objAddResponse           = new AddResponse();
            ContactInfoRepository objContactInfoRepository = new ContactInfoRepository();

            try
            {
                #region [Validation]
                bool bolCheckSign = Utility.CheckSHA(objAddRequest.Sign.Trim(), GetSign(objAddRequest, ApiSignKey));
                if (!bolCheckSign)
                {
                    objAddResponse.Result = $"{MsgFail} : Sign Validate Error";
                    return(objAddResponse);
                }
                #endregion

                #region [Logic]
                ContactInfoData objContactInfoData = new ContactInfoData();
                objContactInfoData.Name     = objAddRequest.Name.Trim();
                objContactInfoData.Nickname = (!string.IsNullOrWhiteSpace(objAddRequest.Nickname) ? objAddRequest.Nickname.Trim() : null);
                objContactInfoData.Gender   = (ContactInfoData.EnumGender?)objAddRequest.Gender;
                objContactInfoData.Age      = objAddRequest.Age;
                objContactInfoData.PhoneNo  = objAddRequest.PhoneNo.Trim();
                objContactInfoData.Address  = objAddRequest.Address.Trim();

                bool bolAddResult = objContactInfoRepository.AddContactInfo(objContactInfoData);
                if (bolAddResult)
                {
                    objAddResponse.Result = MsgSuccess;
                    objAddResponse.Data   = objContactInfoData;
                    objAddResponse.Sign   = GetSign(objAddResponse, ApiSignKey);
                }
                else
                {
                    objAddResponse.Result = $"{MsgFail} : Add Data Error";
                }

                return(objAddResponse);

                #endregion
            }
            catch (Exception ex)
            {
                #region [Exception]
                objAddResponse.Result = $"{MsgException} : {ex.Message}";
                return(objAddResponse);

                #endregion
            }
        }
コード例 #31
0
        public async void ExecuteCalculatorAddRequest()
        {
            AddRequest request = new AddRequest()
            {
                intA = UnityEngine.Random.Range(-byte.MaxValue, byte.MaxValue),
                intB = UnityEngine.Random.Range(-byte.MaxValue, byte.MaxValue)
            };
            //AddResponse response = await _calculatorClient.RequestAsync<AddResponse, AddRequest>("Add", request);
            AddResponse response = await Add.Execute(_calculatorClient, request);

            if (response != null)
            {
                _results.text = string.Format("{0} + {1} = {2}", request.intA, request.intB, response.Value) + Environment.NewLine;
            }
        }
コード例 #32
0
        // Token: 0x06000201 RID: 513 RVA: 0x000059E8 File Offset: 0x00003BE8
        public SyncStatus GetAddResponseStatus(int index)
        {
            if (this.AddResponses == null || this.AddResponses.Count <= index || this.AddResponses[index] == null)
            {
                throw new ArgumentOutOfRangeException("index");
            }
            AddResponse addResponse = this.AddResponses[index];
            byte        status      = addResponse.Status;

            if (!SyncResponse.StatusToEnumMap.ContainsKey(status))
            {
                return((SyncStatus)status);
            }
            return(SyncResponse.StatusToEnumMap[status]);
        }
コード例 #33
0
 /// <summary>
 /// Add new expense record to database
 /// </summary>
 /// <param name="userId">User Identifier</param>
 /// <param name="entity">Expense record</param>
 /// <returns>Expense record identifier</returns>
 public AddResponse Add(int userId, ExpenseRecord entity)
 {
     var response = new AddResponse();
     if (entity == null)
     {
         response.Errors.Add(Error.ExpenseRecordHasNotBeenSet);
         response.IsError = true;
     }
     else
     {
         context.ExpenseRecords.AddObject(entity);
         context.Save();
         response.Id = entity.Id;
     }
     return response;
 }
コード例 #34
0
    private bool AddItemToCart(int title_id, string sku, int quantity, out AddResponse result)
    {
        result = AddResponse.Failure;

        bool success = false; //Duncan Working
        CartDB db = new CartDB();

        DataSet ds = db.CartProductGetBySKU(sku);
        if (ds == null) return false;

        bool is_bulk = false, is_student = false;

        using (DataTableReader data = ds.CreateDataReader())
        {
            while (data.Read())
            {
                is_bulk = data.GetInt32(data.GetOrdinal("IsBulk")) == 1;
                is_student = data.GetInt32(data.GetOrdinal("IsStudent")) == 1;
                break;
            }
        }

        if (is_bulk)
        {
            result |= AddResponse.Bulk;
            return false;
        }

        success = db.CartAddSKU(CurrentCart.CartId, sku, quantity);

        if (success)
        {
            result = AddResponse.Success;
        }

        if (is_student)
        {
            result |= AddResponse.Student;
        }

        return success;
    }
コード例 #35
0
        /// <summary>
        /// Add expense record to the system
        /// </summary>
        /// <param name="userId">User identifier</param>
        /// <param name="description">Description for expense record</param>
        /// <param name="price">Price</param>
        /// <param name="tagId">Tag identifier for expense record</param>
        /// <param name="dateStamp">Date stamp which shows when money were spent</param>
        /// <returns>Executin result as Response object</returns>
        public Response Add(int userId, string description, decimal price, int tagId, DateTime? dateStamp)
        {
            var response = new AddResponse();

            if (string.IsNullOrEmpty(description) || price == 0 || tagId == 0 || dateStamp == null)
            {
                response.IsError = true;
                response.Errors.Add(Error.ExpenseRecordHasNotBeenSet);
            }
            else
            {
                var expenseRecord = new ExpenseRecord();
                var tagRepository = new TagRepository(context);
                expenseRecord.Tag = tagRepository.GetById(userId, tagId).Object;
                expenseRecord.Description = description;
                expenseRecord.Price = price;
                expenseRecord.DateStamp = (DateTime)dateStamp;
                response = Add(userId, expenseRecord);
            }
            return response;
        }
コード例 #36
0
ファイル: TagRepository.cs プロジェクト: sergkl/ExpenseSystem
 /// <summary>
 /// Add new tag to database
 /// </summary>
 /// <param name="userId">User Identifier</param>
 /// <param name="entity">Tag</param>
 /// <returns>Tag identifier</returns>
 public AddResponse Add(int userId, Tag entity)
 {
     var addResponse = new AddResponse();
     if (entity == null)
     {
         addResponse.IsError = true;
         addResponse.Errors.Add(Error.TagNameHasNotBeenSet);
     }
     else
     {
         entity.User = new UserRepository(context).GetById(userId, userId).Object;
         context.Tags.AddObject(entity);
         context.Save();
         addResponse.Id = entity.Id;
     }
     return addResponse;
 }
コード例 #37
0
    private void Redirect(int title_id, AddResponse r)
    {
        if (Request.UrlReferrer != null)
        {
            StringBuilder redirect_uri = new StringBuilder(Request.UrlReferrer.OriginalString);

            string prefix = "";
            string url = string.Format("add_tid={2}&add_response={1}", title_id, (int)r);

            if (Request.UrlReferrer.Query != null && Request.UrlReferrer.Query.Length > 0)
            {
                prefix = "&";
            }
            else
            {
                prefix = "?";
            }

            redirect_uri.AppendFormat("{0}{1}", prefix, url);

            Response.Redirect(redirect_uri.ToString());
        }
    }
コード例 #38
0
        /// <summary>
        /// Creates an AddResponse packet.
        /// </summary>
        /// <param name="context">The user context which contains message ID.</param>
        /// <param name="resultCode">Result code of previous request, as specified in RFC 2251.</param>
        /// <param name="matchedDn">Matched DN.</param>
        /// <param name="errorMessage">Error message for result code. Required.</param>
        /// <param name="referral">Referral. Optional. Used for LDAP v3 only.</param>
        /// <returns>The packet that contains the response.</returns>
        internal override AdtsAddResponsePacket CreateAddResponse(
            AdtsLdapContext context,
            MsLdap.ResultCode resultCode,
            string matchedDn,
            string errorMessage,
            string[] referral)
        {
            AddResponse addResponse = new AddResponse(
                new LDAPResult_resultCode((long)resultCode),
                new LDAPDN(matchedDn ?? string.Empty),
                new LDAPString(errorMessage ?? string.Empty),
                CreateReferral(referral));

            LDAPMessage_protocolOp operation = new LDAPMessage_protocolOp();
            operation.SetData(LDAPMessage_protocolOp.addResponse, addResponse);

            LDAPMessage message = new LDAPMessage(new MessageID(context.MessageId), operation, null);
            AdtsAddResponsePacket packet = new AdtsAddResponsePacket();
            packet.ldapMessagev3 = message;
            packet.messageId = context.MessageId;

            return packet;
        }
コード例 #39
0
 private string BuildResponse(AddResponse response_type)
 {
     StringBuilder output = new StringBuilder();
     //output.Append(Enum.Format(typeof(AddResponse), response_type, "f"));
     output.Append(Enum.Format(typeof(AddResponse), response_type, "d"));
     return output.ToString();
 }