Example #1
0
        internal StreamReadBuffer(Stream source, int initialSize, int maxSize, bool minimalRead)
        {
            StreamWrapper wrapper;
            if (!_lockObjects.TryGetValue(source, out wrapper))
            {
                _lockObjects.Add(source, new StreamWrapper { Source = source });
                wrapper = _lockObjects[source];

                if (source.CanSeek)
                {
                    // assume that this is a quick operation
                    wrapper.EofOffset = source.Length;
                }
            }
            else
            {
                wrapper.RefCount++;
            }

            // make sure our initial size is a power of 2 (this makes resizing simpler to understand)
            initialSize = 2 << (int)Math.Log(initialSize - 1, 2);

            // make sure our max size is a power of 2 (in this case, just so we report a "real" number)
            maxSize = 1 << (int)Math.Log(maxSize, 2);

            _wrapper = wrapper;
            _data = new byte[initialSize];
            _maxSize = maxSize;
            _minimalRead = minimalRead;

            _savedBuffers = new List<SavedBuffer>();
        }
Example #2
0
        public override async Task ExecuteResultAsync([NotNull] ActionContext context)
        {
            var viewEngine = ViewEngine ?? context.HttpContext.RequestServices.GetService<ICompositeViewEngine>();

            var viewName = ViewName ?? context.ActionDescriptor.Name;
            var view = FindView(viewEngine, context, viewName);

            using (view as IDisposable)
            {
                context.HttpContext.Response.ContentType = "text/html; charset=utf-8";
                var wrappedStream = new StreamWrapper(context.HttpContext.Response.Body);
                var encoding = Encodings.UTF8EncodingWithoutBOM;
                using (var writer = new StreamWriter(wrappedStream, encoding, BufferSize, leaveOpen: true))
                {
                    try
                    {
                        var viewContext = new ViewContext(context, view, ViewData, writer);
                        await view.RenderAsync(viewContext);
                    }
                    catch
                    {
                        // Need to prevent writes/flushes on dispose because the StreamWriter will flush even if
                        // nothing got written. This leads to a response going out on the wire prematurely in case an
                        // exception is being thrown inside the try catch block.
                        wrappedStream.BlockWrites = true;
                        throw;
                    }
                }
            }
        }
Example #3
0
        /// <summary>
        /// Asynchronously renders the specified <paramref name="view"/> to the response body.
        /// </summary>
        /// <param name="view">The <see cref="IView"/> to render.</param>
        /// <param name="actionContext">The <see cref="ActionContext"/> for the current executing action.</param>
        /// <param name="viewData">The <see cref="ViewDataDictionary"/> for the view being rendered.</param>
        /// <param name="tempData">The <see cref="ITempDataDictionary"/> for the view being rendered.</param>
        /// <returns>A <see cref="Task"/> that represents the asychronous rendering.</returns>
        public static async Task ExecuteAsync([NotNull] IView view,
                                              [NotNull] ActionContext actionContext,
                                              [NotNull] ViewDataDictionary viewData,
                                              [NotNull] ITempDataDictionary tempData,
                                              string contentType)
        {
            if (string.IsNullOrEmpty(contentType))
            {
                contentType = ContentType;
            }

            actionContext.HttpContext.Response.ContentType = contentType;
            var wrappedStream = new StreamWrapper(actionContext.HttpContext.Response.Body);
            var encoding = Encodings.UTF8EncodingWithoutBOM;
            using (var writer = new StreamWriter(wrappedStream, encoding, BufferSize, leaveOpen: true))
            {
                try
                {
                    var viewContext = new ViewContext(actionContext, view, viewData, tempData, writer);
                    await view.RenderAsync(viewContext);
                }
                catch
                {
                    // Need to prevent writes/flushes on dispose because the StreamWriter will flush even if
                    // nothing got written. This leads to a response going out on the wire prematurely in case an
                    // exception is being thrown inside the try catch block.
                    wrappedStream.BlockWrites = true;
                    throw;
                }
            }
        }
        private void HandleRequest()
        {
            if (Context.Request.Files.Count > 1 && _associationId.HasValue)
                throw new HttpException("AID must be provided in request with multiple file uploads");

            for (int i = 0; i < Context.Request.Files.Count; i++)
            {
                var file = Context.Request.Files[i];

                string associationIdString = Context.Request.Form["AID_" + i];

                if (
                    associationIdString == null &&
                    (!_associationId.HasValue || Context.Request.Form.Count > 1)
                )
                    throw new HttpException("AID wasn't provided in the request");

                int associationId;

                if (_associationId.HasValue)
                    associationId = _associationId.Value;
                else if (!int.TryParse(associationIdString, out associationId))
                    throw new HttpException("Invalid AID");

                var wrappedStream = new StreamWrapper(file.InputStream);

                wrappedStream.Closed += wrappedStream_Closed;

                int responseId = _client.Client.SendStream(wrappedStream, file.FileName, file.ContentType, associationId);

                Debug.Assert(associationId == responseId);
            }
        }
Example #5
0
		/// <summary>
		/// Merges the path with the current working directory
		/// to get a canonicalized absolute pathname representing the same file.
		/// </summary>
		/// <remarks>
		/// This method is an analogy of <c>main/safe_mode.c: php_checkuid</c>.
		/// Looks for the file in the <c>include_path</c> and checks for <c>open_basedir</c> restrictions.
		/// </remarks>
		/// <param name="path">An absolute or relative path to a file.</param>
		/// <param name="wrapper">The wrapper found for the specified file or <c>null</c> if the path resolution fails.</param>
		/// <param name="mode">The checking mode of the <see cref="CheckAccess"/> method (file, directory etc.).</param>
		/// <param name="options">Additional options for the <see cref="CheckAccess"/> method.</param>
		/// <returns><c>true</c> if all the resolution and checking passed without an error, <b>false</b> otherwise.</returns>
		/// <exception cref="PhpException">Security violation - when the target file 
		/// lays outside the tree defined by <c>open_basedir</c> configuration option.</exception>
		public static bool ResolvePath(ref string path, out StreamWrapper wrapper, CheckAccessMode mode, CheckAccessOptions options)
		{
			// Path will contain the absolute path without file:// or the complete URL; filename is the relative path.
			string filename, scheme = GetSchemeInternal(path, out filename);
			wrapper = StreamWrapper.GetWrapper(scheme, (StreamOptions)options);
			if (wrapper == null) return false;

			if (wrapper.IsUrl)
			{
				// Note: path contains the whole URL, filename the same without the scheme:// portion.
				// What to check more?
			}
			else if (scheme != "php")
			{
				// SILVERLIGHT: ?? what to do here ??
				// PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_access_denied", path));
			}

			return true;
		}
Example #6
0
		public void AddResource (string name, object value)
		{
			if (name == null)
				throw new ArgumentNullException ("name");
			if (resources == null)
				throw new InvalidOperationException ("The resource writer has already been closed and cannot be edited");
			if (resources[name] != null)
				throw new ArgumentException ("Resource already present: " + name);
#if NET_4_0
			if (value is Stream) {
				Stream stream = value as Stream;
				if (!stream.CanSeek)
					throw new ArgumentException ("Stream does not support seeking.");

				if (!(value is MemoryStream)) // We already support MemoryStream
					value = new StreamWrapper (stream, false);
			}
#endif

			resources.Add(name, value);
		}
 public override void ReadPacketData(StreamWrapper buff)
 {
     throw new NotImplementedException();
 }
Example #8
0
 public Registrator()
 {
     PhpFilter.AddFilterFactory(new ZlibFilterFactory());
     StreamWrapper.RegisterSystemWrapper(new ZlibStreamWrapper());
     RegisterLegacyOptions();
 }
Example #9
0
 public override void ReadPacketData(StreamWrapper buff)
 {
     WindowId = buff.ReadByte();
 }
Example #10
0
        /// <summary>
        /// This method is used to download the bulk read job as a CSV or an ICS file (only for the Events module).
        /// </summary>
        /// <param name="jobId">The unique ID of the bulk read job.</param>
        /// <param name="destinationFolder">The absolute path where downloaded file has to be stored.</param>
        public static void DownloadResult(long jobId, string destinationFolder)
        {
            //example
            //long jobId = 34770615177002;
            //string destinationFolder = "/Users/user_name/Documents";

            //Get instance of BulkReadOperations Class
            BulkReadOperations bulkReadOperations = new BulkReadOperations();

            //Call DownloadResult method that takes jobId as parameters
            APIResponse <API.BulkRead.ResponseHandler> response = bulkReadOperations.DownloadResult(jobId);

            if (response != null)
            {
                //Get the status code from response
                Console.WriteLine("Status Code: " + response.StatusCode);

                if (new List <int>()
                {
                    204, 304
                }.Contains(response.StatusCode))
                {
                    Console.WriteLine(response.StatusCode == 204 ? "No Content" : "Not Modified");

                    return;
                }

                //Check if expected response is received
                if (response.IsExpected)
                {
                    //Get object from response
                    API.BulkRead.ResponseHandler responseHandler = response.Object;

                    if (responseHandler is FileBodyWrapper)
                    {
                        //Get the received FileBodyWrapper instance
                        FileBodyWrapper fileBodyWrapper = (FileBodyWrapper)responseHandler;

                        //Get StreamWrapper instance from the returned FileBodyWrapper instance
                        StreamWrapper streamWrapper = fileBodyWrapper.File;

                        Stream file = streamWrapper.Stream;

                        string fullFilePath = Path.Combine(destinationFolder, streamWrapper.Name);

                        using (FileStream outputFileStream = new FileStream(fullFilePath, FileMode.Create))
                        {
                            file.CopyTo(outputFileStream);
                        }
                    }
                    //Check if the request returned an exception
                    else if (responseHandler is API.BulkRead.APIException)
                    {
                        //Get the received APIException instance
                        API.BulkRead.APIException exception = (APIException)responseHandler;

                        //Get the Status
                        Console.WriteLine("Status: " + exception.Status.Value);

                        //Get the Code
                        Console.WriteLine("Code: " + exception.Code.Value);

                        Console.WriteLine("Details: ");

                        //Get the details map
                        foreach (KeyValuePair <string, object> entry in exception.Details)
                        {
                            //Get each value in the map
                            Console.WriteLine(entry.Key + ": " + JsonConvert.SerializeObject(entry.Value));
                        }

                        //Get the Message
                        Console.WriteLine("Message: " + exception.Message.Value);
                    }
                }
                else
                {                 //If response is not as expected
                    //Get model object from response
                    Model responseObject = response.Model;

                    //Get the response object's class
                    Type type = responseObject.GetType();

                    //Get all declared fields of the response class
                    Console.WriteLine("Type is: {0}", type.Name);

                    PropertyInfo[] props = type.GetProperties();

                    Console.WriteLine("Properties (N = {0}):", props.Length);

                    foreach (var prop in props)
                    {
                        if (prop.GetIndexParameters().Length == 0)
                        {
                            Console.WriteLine("{0} ({1}) : {2}", prop.Name, prop.PropertyType.Name, prop.GetValue(responseObject));
                        }
                        else
                        {
                            Console.WriteLine("{0} ({1}) : <Indexed>", prop.Name, prop.PropertyType.Name);
                        }
                    }
                }
            }
        }
Example #11
0
 private string GetResponseFromWebResponseWrapped(WebResponseWrapper responseWrapper)
 {
     string responseText;
     using (var tokenResponseWrapper = new StreamWrapper(responseWrapper.Get().GetResponseStream()))
     {
         InvokeLog("Token Response: " + tokenResponseWrapper.Get());
         if (tokenResponseWrapper.Get() == null) { throw new AcsApiException(AcsApiError.CouldNotGetAccesstoken); }
         using (var reader = new StreamReader(tokenResponseWrapper.Get(), Encoding.ASCII))
         {
             responseText = reader.ReadToEnd();
             reader.Close();
         }
     }
     return responseText;
 }
Example #12
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            DA.DisableGapLogic();
            if (DA.Iteration != 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning,
                                  "Cannot fetch multiple streams at the same time. This is an explicit guard against possibly unintended behaviour. If you want to get the details of another stream, please use a new component.");
                return;
            }

            string           userId      = null;
            GH_SpeckleStream ghIdWrapper = null;

            DA.DisableGapLogic();
            DA.GetData(0, ref ghIdWrapper);
            DA.GetData(1, ref userId);
            var account = string.IsNullOrEmpty(userId) ? AccountManager.GetDefaultAccount() :
                          AccountManager.GetAccounts().FirstOrDefault(a => a.userInfo.id == userId);

            var idWrapper = ghIdWrapper.Value;

            if (account == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Could not find default account in this machine. Use the Speckle Manager to add an account.");
                return;
            }

            Params.Input[1].AddVolatileData(new GH_Path(0), 0, account.userInfo.id);

            if (error != null)
            {
                Message = null;
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, error.Message);
                error  = null;
                stream = null;
            }
            else if (stream == null)
            {
                Message = "Fetching";
                // Validation
                string errorMessage = null;
                if (!ValidateInput(account, idWrapper.StreamId, ref errorMessage))
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, errorMessage);
                    return;
                }

                // Run
                Task.Run(async() =>
                {
                    try
                    {
                        //Exists?
                        var client        = new Client(account);
                        var result        = await client.StreamGet(idWrapper.StreamId);
                        stream            = new StreamWrapper(result.id, account.userInfo.id, account.serverInfo.url);
                        stream.BranchName = idWrapper.BranchName;
                        stream.ObjectId   = idWrapper.ObjectId;
                        stream.CommitId   = idWrapper.CommitId;
                    }
                    catch (Exception e)
                    {
                        stream = null;
                        error  = e;
                    }
                    finally
                    {
                        Rhino.RhinoApp.InvokeOnUiThread((Action) delegate { ExpireSolution(true); });
                    }
                });
            }
            else
            {
                Message = "Done";
                DA.SetData(0, new GH_SpeckleStream(stream));
                stream = null;
            }
        }
		public void Load (Uri uri)
		{
			this.uri = uri;

			delay.Stop ();

			if (!done_reading)
				Close ();

			done_reading = false;
			area_prepared = false;
			damage = Gdk.Rectangle.Zero;

			using (ImageFile img = ImageFile.Create (uri)) {
				orientation = Accelerometer.GetViewOrientation (img.Orientation);
			
				try {
					PixbufOrientation thumb_orientation = Accelerometer.GetViewOrientation (PixbufOrientation.TopLeft);
					thumb = new Gdk.Pixbuf (ThumbnailGenerator.ThumbnailPath (uri));
					thumb = PixbufUtils.TransformOrientation (thumb, thumb_orientation);
					
					if (FSpot.ColorManagement.IsEnabled && !thumb.HasAlpha) {
						if (img.GetProfile () == null)
							FSpot.ColorManagement.PhotoImageView.Transform = FSpot.ColorManagement.StandartTransform ();
						else
							FSpot.ColorManagement.PhotoImageView.Transform = FSpot.ColorManagement.CreateTransform (thumb, img.GetProfile ());
					}
					else
						FSpot.ColorManagement.PhotoImageView.Transform = null;
				} catch (System.Exception e) {
					//FSpot.ThumbnailGenerator.Default.Request (uri.ToString (), 0, 256, 256);	
					if (!(e is GLib.GException)) 
						System.Console.WriteLine (e.ToString ());
				}

				System.IO.Stream nstream = img.PixbufStream ();
				if (nstream == null) {
					FileLoad (img);
					return;
				} else
					stream = new StreamWrapper (nstream);

				loader = new Gdk.PixbufLoader ();
				loader.AreaPrepared += ap;
				loader.AreaUpdated += au;
				loader.Closed += ev;

				if (AreaPrepared != null && thumb != null) {
					pixbuf = thumb;
					AreaPrepared (this, new AreaPreparedArgs (true));
				}

				ThumbnailGenerator.Default.PushBlock ();
				//AsyncIORead (null);
				if (nstream is IOChannel) {
					((IOChannel)nstream).DataReady += IOChannelRead;
				} else
					delay.Start ();
			}

		}			
		private void Close () {
			ThumbnailGenerator.Default.PopBlock ();
				
			try {
				result = null;

				delay.Stop ();
				if (loader != null) { 
					loader.AreaPrepared -= ap;
					loader.AreaUpdated -= au;
					// this can throw exceptions
					loader.Close ();
				}
			} catch (System.Exception) {
				//System.Console.WriteLine (e.ToString ());
				if (pixbuf != null)
					pixbuf.Dispose ();

				pixbuf = null;
			} finally {
				if (loader != null) {
					loader.Closed -= ev;
					loader.Dispose ();
				}

				loader = null;

				if (stream != null) 
					stream.Close ();

				stream = null;
			}
		}
Example #15
0
 public override void WritePacketData(StreamWrapper buff)
 {
 }
Example #16
0
        /// <summary>
        /// This method is used to upload an attachment to a single record of a module with ID and print the response.
        /// </summary>
        /// <param name="moduleAPIName">The API Name of the record's module</param>
        /// <param name="recordId">The ID of the record to upload attachment</param>
        /// <param name="absoluteFilePath">The absolute file path of the file to be attached</param>
        public static void UploadAttachments(string moduleAPIName, long recordId, string absoluteFilePath)
        {
            //example
            //string moduleAPIName = "Leads";
            //long recordId = 34770615177002;
            //string absoluteFilePath = "/Users/use_name/Desktop/image.png";

            //Get instance of AttachmentsOperations Class that takes moduleAPIName and recordId as parameter
            AttachmentsOperations attachmentsOperations = new AttachmentsOperations(moduleAPIName, recordId);

            //Get instance of FileBodyWrapper class that will contain the request file
            API.Attachments.FileBodyWrapper fileBodyWrapper = new API.Attachments.FileBodyWrapper();

            //Get instance of StreamWrapper class that takes absolute path of the file to be attached as parameter
            StreamWrapper streamWrapper = new StreamWrapper(absoluteFilePath);

            //Set file to the FileBodyWrapper instance
            fileBodyWrapper.File = streamWrapper;

            //Call UploadAttachment method that takes FileBodyWrapper instance as parameter
            APIResponse <API.Attachments.ActionHandler> response = attachmentsOperations.UploadAttachment(fileBodyWrapper);

            if (response != null)
            {
                //Get the status code from response
                Console.WriteLine("Status Code: " + response.StatusCode);

                //Check if expected response is received
                if (response.IsExpected)
                {
                    //Get object from response
                    API.Attachments.ActionHandler actionHandler = response.Object;

                    if (actionHandler is API.Attachments.ActionWrapper)
                    {
                        //Get the received ActionWrapper instance
                        API.Attachments.ActionWrapper actionWrapper = (API.Attachments.ActionWrapper)actionHandler;

                        //Get the list of obtained action responses
                        List <API.Attachments.ActionResponse> actionResponses = actionWrapper.Data;

                        foreach (API.Attachments.ActionResponse actionResponse in actionResponses)
                        {
                            //Check if the request is successful
                            if (actionResponse is API.Attachments.SuccessResponse)
                            {
                                //Get the received SuccessResponse instance
                                API.Attachments.SuccessResponse successResponse = (API.Attachments.SuccessResponse)actionResponse;

                                //Get the Status
                                Console.WriteLine("Status: " + successResponse.Status.Value);

                                //Get the Code
                                Console.WriteLine("Code: " + successResponse.Code.Value);

                                Console.WriteLine("Details: ");

                                if (successResponse.Details != null)
                                {
                                    //Get the details map
                                    foreach (KeyValuePair <string, object> entry in successResponse.Details)
                                    {
                                        //Get each value in the map
                                        Console.WriteLine(entry.Key + " : " + JsonConvert.SerializeObject(entry.Value));
                                    }
                                }

                                //Get the Message
                                Console.WriteLine("Message: " + successResponse.Message.Value);
                            }
                            //Check if the request returned an exception
                            else if (actionResponse is API.Attachments.APIException)
                            {
                                //Get the received APIException instance
                                API.Attachments.APIException exception = (API.Attachments.APIException)actionResponse;

                                //Get the Status
                                Console.WriteLine("Status: " + exception.Status.Value);

                                //Get the Code
                                Console.WriteLine("Code: " + exception.Code.Value);

                                Console.WriteLine("Details: ");

                                if (exception.Details != null)
                                {
                                    //Get the details map
                                    foreach (KeyValuePair <string, object> entry in exception.Details)
                                    {
                                        //Get each value in the map
                                        Console.WriteLine(entry.Key + " : " + JsonConvert.SerializeObject(entry.Value));
                                    }
                                }

                                //Get the Message
                                Console.WriteLine("Message: " + exception.Message.Value);
                            }
                        }
                    }
                    //Check if the request returned an exception
                    else if (actionHandler is API.Attachments.APIException)
                    {
                        //Get the received APIException instance
                        API.Attachments.APIException exception = (API.Attachments.APIException)actionHandler;

                        //Get the Status
                        Console.WriteLine("Status: " + exception.Status.Value);

                        //Get the Code
                        Console.WriteLine("Code: " + exception.Code.Value);

                        Console.WriteLine("Details: ");

                        if (exception.Details != null)
                        {
                            //Get the details map
                            foreach (KeyValuePair <string, object> entry in exception.Details)
                            {
                                //Get each value in the map
                                Console.WriteLine(entry.Key + ": " + JsonConvert.SerializeObject(entry.Value));
                            }
                        }

                        //Get the Message
                        Console.WriteLine("Message: " + exception.Message.Value);
                    }
                }
                else
                {                 //If response is not as expected
                    //Get model object from response
                    Model responseObject = response.Model;

                    //Get the response object's class
                    Type type = responseObject.GetType();

                    //Get all declared fields of the response class
                    Console.WriteLine("Type is: {0}", type.Name);

                    PropertyInfo[] props = type.GetProperties();

                    Console.WriteLine("Properties (N = {0}):", props.Length);

                    foreach (var prop in props)
                    {
                        if (prop.GetIndexParameters().Length == 0)
                        {
                            Console.WriteLine("{0} ({1}) : {2}", prop.Name, prop.PropertyType.Name, prop.GetValue(responseObject));
                        }
                        else
                        {
                            Console.WriteLine("{0} ({1}) : <Indexed>", prop.Name, prop.PropertyType.Name);
                        }
                    }
                }
            }
        }
Example #17
0
 public override void ReadPacketData(StreamWrapper buff)
 {
 }
Example #18
0
 public void Initialize(IStream stream, int grfMode)
 {
     // IStream passed to our wrapper which handles our clean up
     this.stream = new StreamWrapper(stream);
 }
Example #19
0
        private void LoadFssToken()
        {
            // Creating a new instance directly
            var client = new OAuthRequest
            {
                Method = "GET",
                Type = OAuthRequestType.RequestToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey = serviceConfig.ConsumerKey,
                ConsumerSecret = serviceConfig.ConsumerSecret,
                RequestUrl = serviceConfig.ServerRoot + AcsApiClientConfig.RequestUrl,
                CallbackUrl = serviceConfig.ServerRoot + "client"
            };


            //CookieCollection responseCookies = null;
            string setCookieHeader;
            var fields = new Hashtable();
            using (var responseWrapper = new WebResponseWrapper(RequestToken(client)))
            {
                var responseText = GetResponseFromWebResponseWrapped(responseWrapper);

                for (var i = 0; i < responseText.Split('&').Length; i++)
                {
                    var fieldInfo = responseText.Split('&')[i].Split('=');
                    fields[fieldInfo[0]] = fieldInfo[1];
                }

                //responseCookies = responseWrapper.Get().Cookies;
                setCookieHeader = responseWrapper.Get().Headers["Set-Cookie"];
            }

            var myHttpWebRequest = Login(client, setCookieHeader, fields);

            string jsessionid;
            setCookieHeader = null;
            try
            {
                using (var responseWrapper = new WebResponseWrapper((HttpWebResponse)myHttpWebRequest.GetResponse()))
                {
                    setCookieHeader = responseWrapper.Get().Headers["Set-Cookie"];
                    var sessionCookie = responseWrapper.Get().Cookies[SessionIdKey];
                    if (sessionCookie != null)
                    {
                        jsessionid = sessionCookie.Value;

                        InvokeLog("Jsesssion found at " + jsessionid);
                        cookies.Add(sessionCookie);
                    }
                    else
                    {
                        throw new InvalidOperationException("JSession Id returned null!");
                    }
                }
            }
            catch (WebException wex)
            {
                throw new AcsApiException(AcsApiError.ServerError.ToString(), wex);
            }

            var target = new Uri(serviceConfig.ServerRoot);
            var cdomain = target.Host;

            string[] locations;
            using (var responseWrapper = new WebResponseWrapper(ConsumerHandshake(client, jsessionid, setCookieHeader, cdomain)))
            {
                locations = responseWrapper.Get().Headers.GetValues("location");
                setCookieHeader = responseWrapper.Get().Headers["Set-Cookie"];
            }

            if (locations == null)
            {
                throw new AcsApiException(AcsApiError.CouldNotLogin);
            }

            var myUri = new Uri(locations.FirstOrDefault() ?? string.Empty);
            InvokeLog("Request for uri" + myUri);
            if (string.IsNullOrEmpty(myUri.Query))
            {
                // No oauth_token or oauth_verifier in location header, so didn't authenticate.
                throw new AcsApiException(AcsApiError.CouldNotLogin);
            }

            var accessToken = HttpUtility.ParseQueryString(myUri.Query).Get(OauthTokenKey);
            var oauthVerifier = HttpUtility.ParseQueryString(myUri.Query).Get(OauthVerifierKey);

            InvokeLog("Verifier response " + accessToken + " : " + oauthVerifier);

            if (string.IsNullOrEmpty(oauthVerifier))
            {
                throw new AcsApiException(AcsApiError.CouldNotFindVerifier);
            }

            using (var requestWrapper = new WebResponseWrapper(RequestFinal(client, accessToken, oauthVerifier, cdomain, setCookieHeader)))
            {
                using (var responseStream = new StreamWrapper(requestWrapper.Get().GetResponseStream()))
                {
                    if (responseStream.Get() == null)
                    {
                        throw new AcsApiException(AcsApiError.CouldNotGetAccesstoken);
                    }

                    string responseOutput;

                    // Pipes the stream to a higher level stream reader with the required encoding format. 
                    using (var readStream = new StreamReader(responseStream.Get(), Encoding.UTF8))
                    {
                        responseOutput = readStream.ReadToEnd();
                    }

                    serviceConfig.AccessToken = HttpUtility.ParseQueryString(responseOutput).Get(OauthTokenKey);
                    serviceConfig.AccessTokenSecret = HttpUtility.ParseQueryString(responseOutput).Get(OauthTokenSecretKey);

                    InvokeLog("Final Tokens: " + serviceConfig.AccessToken + " : " + serviceConfig.AccessTokenSecret);
                }
            }
        }
Example #20
0
        private IEnumerable<BytesWraper> ReceiveMessageBodyChunkedZip()
        {
            var bytesWraper = new BytesWraper();
            var streamWrapper = new StreamWrapper
                (_request.ClientStream, _receiverHelper);

            using (Stream stream = GetZipStream(streamWrapper))
            {
                int bufferSize = _request.TcpClient.ReceiveBufferSize;
                byte[] buffer = new byte[bufferSize];

                bytesWraper.Value = buffer;

                while (true)
                {
                    string line = _receiverHelper.ReadLine();

                    // Если достигнут конец блока.
                    if (line.Equals(
                        HttpHelper.NewLine, StringComparison.Ordinal))
                    {
                        continue;
                    }

                    line = line.Trim(' ', '\r', '\n');

                    // Если достигнут конец данных.
                    if (line.Equals("0", StringComparison.Ordinal))
                    {
                        yield break;
                    }

                    int blockLength;

                    #region Задаём длину блока

                    try
                    {
                        blockLength = Convert.ToInt32(line, 16);
                    }
                    catch (Exception ex)
                    {
                        if (ex is FormatException || ex is OverflowException)
                        {
                            throw NewHttpException(string.Format(
                                Resources.HttpException_WrongChunkedBlockLength, line), ex);
                        }

                        throw;
                    }

                    #endregion

                    streamWrapper.TotalBytesRead = 0;
                    streamWrapper.LimitBytesRead = blockLength;

                    while (true)
                    {
                        int bytesRead = stream.Read(buffer, 0, bufferSize);

                        if (bytesRead == 0)
                        {
                            if (streamWrapper.TotalBytesRead == blockLength)
                            {
                                break;
                            }
                            else
                            {
                                WaitData();

                                continue;
                            }
                        }

                        bytesWraper.Length = bytesRead;
                        yield return bytesWraper;
                    }
                }
            }
        }
		async Task RunWithManualClient (TestContext ctx, CancellationToken cancellationToken)
		{
			ctx.LogMessage ("MANUAL CLIENT");

			var serverStream = new StreamWrapper (Server.Stream);
			await serverStream.WriteLineAsync ("Hello World!");

			ctx.LogMessage ("WAITING FOR CLIENT INPUT");

			var line = await serverStream.ReadLineAsync ();
			ctx.LogMessage ("GOT CLIENT MESSAGE: {0}", line);

			await Shutdown (ctx, SupportsCleanShutdown, true, cancellationToken);
		}
Example #22
0
        // note: throwing MoonException from here is NOT ok since this code is called async
        // and the exception won't be reported, directly, to the caller
        void AssemblyGetResponse(IAsyncResult result)
        {
            Assembly asm;

            object[]             tuple = (object [])result.AsyncState;
            WebRequest           wreq  = (WebRequest)tuple [0];
            ManifestAssemblyKind kind  = (ManifestAssemblyKind)tuple [1];
            int error_code             = (kind == ManifestAssemblyKind.ExternalAssembly) ? 2152 : 2105;

            try {
                HttpWebResponse wresp = (HttpWebResponse)wreq.EndGetResponse(result);

                if (wresp.StatusCode != HttpStatusCode.OK)
                {
                    wresp.Close();
                    EmitError(error_code, String.Format("Error while downloading the '{0}'.", wreq.RequestUri));
                    return;
                }

                if ((kind != ManifestAssemblyKind.ExternalAssembly) && (wresp.ResponseUri != wreq.RequestUri))
                {
                    wresp.Close();
                    EmitError(error_code, "Redirection not allowed to download assemblies.");
                    return;
                }

                using (Stream responseStream = wresp.GetResponseStream()) {
                    byte [] buffer = AssemblyPart.StreamToBuffer(responseStream);

                    if (IsZip(buffer))
                    {
                        // unzip it.
                        using (MemoryStream dest = new MemoryStream()) {
                            using (MemoryStream source = new MemoryStream(buffer)) {
                                ManagedStreamCallbacks source_cb;
                                ManagedStreamCallbacks dest_cb;
                                StreamWrapper          source_wrapper;
                                StreamWrapper          dest_wrapper;

                                source_wrapper = new StreamWrapper(source);
                                dest_wrapper   = new StreamWrapper(dest);

                                source_cb = source_wrapper.GetCallbacks();
                                dest_cb   = dest_wrapper.GetCallbacks();

                                // Zip files may contain multiple assemblies, all of which need to be loaded. Keep
                                // attempting to open subsequent files until it fails.
                                for (int i = 0; ; i++)
                                {
                                    if (!NativeMethods.managed_unzip_stream_to_stream_nth_file(ref source_cb, ref dest_cb, i))
                                    {
                                        break;
                                    }
                                    if (Load(dest.ToArray(), kind) == null)
                                    {
                                        EmitError(2153, String.Format("Error while loading '{0}'.", wreq.RequestUri));
                                    }
                                    source.Position = 0;
                                    dest.SetLength(0);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (Load(buffer, kind) == null)
                        {
                            EmitError(2153, String.Format("Error while loading '{0}'.", wreq.RequestUri));
                        }
                    }
                }
                Dispatcher.BeginInvoke(AsyncDownloadComplete);
            }
            catch (Exception e) {
                // we need to report everything since any error means CreateApplication won't be called
                EmitError(error_code, e.ToString());
            }
        }
 public SendCommandTask(Command aCommand, StreamWrapper wrapper, AsyncCommandSender anAsyncCommandSender)
 {
     this._command = aCommand;
     this._wrapper = wrapper;
     this._sender  = anAsyncCommandSender;
 }
Example #24
0
        /// <summary>
        /// Check StatInternal input parameters.
        /// </summary>
        /// <param name="path">The path passed to stat().</param>
        /// <param name="quiet">Wheter to suppress warning message if argument is empty.</param>
        /// <param name="wrapper">If passed, it will contain valid StremWrapper to the given <paramref name="path"/>.</param>
        /// <returns>True if check passed.</returns>
        private static bool StatInternalCheck(ref string path, bool quiet, out StreamWrapper wrapper)
        {
            wrapper = null;
            
            if (String.IsNullOrEmpty(path))
            {
                PhpException.Throw(PhpError.Warning, LibResources.GetString("arg:empty", "path"));
                return false;
            }

            CheckAccessOptions options = CheckAccessOptions.Empty;
            if (quiet) options |= CheckAccessOptions.Quiet;
            if (!PhpStream.ResolvePath(ref path, out wrapper, CheckAccessMode.FileOrDirectory, options))
                return false;
            
            // check passed
            return true;
        }
Example #25
0
    /// <summary>
    /// Send validation request to validator and obtain result
    /// </summary>
    /// <param name="validationData">Validator parameters</param>
    /// <param name="parameter">Parameter</param>
    /// <returns>DataSet containing validator response</returns>
    private void GetValidationResults(Dictionary <string, string> validationData, string parameter)
    {
        DataSet       dsResponse    = null;
        List <string> validatedUrls = validationData.Keys.ToList();
        Random        randGen       = new Random();
        DataSet       dsResult      = DataSource = ((validationData.Count == 1) && string.IsNullOrEmpty(validationData[validatedUrls[0]])) ? new DataSet() : null;

        string source  = null;
        int    counter = 0;

        while (validatedUrls.Count > 0)
        {
            // Check if source is processed repeatedly
            if (source == validatedUrls[0])
            {
                counter++;
            }
            else
            {
                counter = 0;
            }

            // Set current source to validate
            source = validatedUrls[0];
            string cssData = validationData[source];
            validatedUrls.RemoveAt(0);

            if (!String.IsNullOrEmpty(cssData))
            {
                // Create web request
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ValidatorURL);
                req.Method = "POST";
                // 1 second for timeout
                req.ReadWriteTimeout = req.Timeout = 10000;

                string boundary = "---------------------------" + randGen.Next(1000000, 9999999) + randGen.Next(1000000, 9999999);
                req.ContentType = "multipart/form-data; boundary=" + boundary;

                // Set data to web request for validation
                byte[] data = Encoding.GetEncoding("UTF-8").GetBytes(GetRequestData(GetRequestDictionary(cssData), boundary));
                req.ContentLength = data.Length;

                try
                {
                    AddLog(String.Format(GetString("validation.css.validatingcss"), source));

                    using (var stream = req.GetRequestStream())
                    {
                        using (var writer = StreamWrapper.New(stream))
                        {
                            writer.Write(data, 0, data.Length);
                            writer.Close();
                        }
                    }

                    // Process server answer
                    using (var webResponse = (HttpWebResponse)req.GetResponse())
                    {
                        using (var response = StreamWrapper.New(webResponse.GetResponseStream()))
                        {
                            if (response != null)
                            {
                                if (dsResult == null)
                                {
                                    dsResult = DataSource = new DataSet();
                                }

                                dsResponse = new DataSet();
                                dsResponse.ReadXml(response.SystemStream);
                                response.Close();
                            }
                        }
                        webResponse.Close();
                    }

                    string[] currentUrlValues = parameter.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                    Dictionary <string, object> parameters = new Dictionary <string, object>();
                    parameters["sitename"]       = SiteContext.CurrentSiteName;
                    parameters["user"]           = mCurrentUser;
                    parameters["source"]         = source;
                    parameters["domainurl"]      = currentUrlValues[0];
                    parameters["applicationurl"] = currentUrlValues[1];

                    DataTable dtResponse = DocumentValidationHelper.ProcessValidationResult(dsResponse, DocumentValidationEnum.CSS, parameters);

                    // Check if response contain any relevant data
                    if (!DataHelper.DataSourceIsEmpty(dtResponse))
                    {
                        // Add response data to validation DataSet
                        if (DataHelper.DataSourceIsEmpty(dsResult))
                        {
                            dsResult.Tables.Add(dtResponse);
                        }
                        else
                        {
                            dsResult.Tables[0].Merge(dtResponse);
                        }
                    }
                }
                catch (WebException)
                {
                    AddError(string.Format(GetString("validation.css.cssnotvalidated"), source));
                }
                catch
                {
                    if (counter < 5)
                    {
                        validatedUrls.Insert(0, source);
                    }
                    else
                    {
                        AddError(string.Format(GetString("validation.css.cssnotvalidated"), source));
                    }
                }
                finally
                {
                    req.Abort();
                    Thread.Sleep(ValidationDelay);
                }
            }
        }
    }
Example #26
0
		/// <summary>
		/// Creates a new <see cref="ExternalStream"/> with the given proxy object.
		/// </summary>
		/// <param name="proxy">Instance of a class derived from <see cref="MarshalByRefObject"/> that should
		/// serve as a proxy for this <see cref="ExternalStream"/>.</param>
		/// <param name="openingWrapper">The parent instance.</param>
		/// <param name="accessOptions">The additional options parsed from the <c>fopen()</c> mode.</param>
		/// <param name="openedPath">The absolute path to the opened resource.</param>
		/// <param name="context">The stream context passed to fopen().</param>
		internal ExternalStream(IExternalStream proxy, StreamWrapper openingWrapper, StreamAccessOptions accessOptions, string openedPath, StreamContext context)
			: base(openingWrapper, accessOptions, openedPath, context)
		{
			this.proxy = proxy;
		}
 public override void ReadPacketData(StreamWrapper buff)
 {
     Health     = buff.ReadSingle();
     Food       = buff.ReadShort();
     Saturation = buff.ReadSingle();
 }
Example #28
0
        public static void TestUpload()
        {
            string boundary = "----FILEBOUNDARY----";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.zohoapis.com/crm/v2/files");

            request.ContentType = "multipart/form-data; boundary=" + boundary;

            request.Method = "POST";

            request.Headers["Authorization"] = "Zoho-oauthtoken 1000.xxxx.xxxxx";

            request.KeepAlive = true;

            Stream memStream = new System.IO.MemoryStream();

            var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--");

            string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n";

            StreamWrapper streamWrapper = new StreamWrapper("/Users/Desktop/test.html");

            StreamWrapper streamWrapper1 = new StreamWrapper("/Users/Desktop/test.html");

            List <StreamWrapper> streamWrapperList = new List <StreamWrapper>()
            {
                streamWrapper, streamWrapper1
            };

            for (int i = 0; i < streamWrapperList.Count; i++)
            {
                StreamWrapper streamWrapperInstance = streamWrapperList[i];

                memStream.Write(boundarybytes, 0, boundarybytes.Length);

                var header = string.Format(headerTemplate, "file", streamWrapperInstance.Name);

                var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

                memStream.Write(headerbytes, 0, headerbytes.Length);

                var buffer = new byte[1024];

                var bytesRead = 0;

                while ((bytesRead = streamWrapperInstance.Stream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    memStream.Write(buffer, 0, bytesRead);
                }
            }

            memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);

            request.ContentLength = memStream.Length;

            using (Stream requestStream = request.GetRequestStream())
            {
                memStream.Position = 0;

                byte[] tempBuffer = new byte[memStream.Length];

                memStream.Read(tempBuffer, 0, tempBuffer.Length);

                memStream.Close();

                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
            }

            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                if (e.Response == null)
                {
                    throw;
                }

                response = (HttpWebResponse)e.Response;
            }

            HttpWebResponse responseEntity = response;

            string responsestring = new StreamReader(responseEntity.GetResponseStream()).ReadToEnd();

            responseEntity.Close();

            Console.WriteLine(responsestring);
        }
Example #29
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            if (DA.Iteration != 0)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Cannot create multiple streams at the same time. This is an explicit guard against possibly unintended behaviour. If you want to create another stream, please use a new component.");
                return;
            }

            string  userId  = null;
            Account account = null;

            DA.GetData(0, ref userId);

            if (userId == null)
            {
                //account = AccountManager.GetDefaultAccount();
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, $"Using default account {account}");
            }
            else
            {
                account = AccountManager.GetAccounts().FirstOrDefault(a => a.userInfo.id == userId);
                if (account == null)
                {
                    // Really last ditch effort - in case people delete accounts from the manager, and the selection dropdown is still using an outdated list.
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"The user with id of {userId} was not found.");
                    return;
                }
            }

            Params.Input[0].AddVolatileData(new GH_Path(0), 0, account.userInfo.id);

            if (stream != null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using cached stream. If you want to create a new stream, create a new component.");
                DA.SetData(0, new GH_SpeckleStream(stream));
                NickName        = $"Id: {stream.StreamId}";
                MutableNickName = false;
                return;
            }

            Task.Run(async() =>
            {
                var client = new Client(account);
                try
                {
                    var streamId = await client.StreamCreate(new StreamCreateInput());
                    stream       = new StreamWrapper(
                        streamId,
                        account.userInfo.id,
                        account.serverInfo.url
                        );

                    Rhino.RhinoApp.InvokeOnUiThread((Action) delegate
                    {
                        ExpireSolution(true);
                    });
                }
                catch (Exception e)
                {
                    Rhino.RhinoApp.InvokeOnUiThread((Action) delegate
                    {
                        ExpireSolution(false);
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"Could not create stream at {account.serverInfo.url}:\n{e.Message}");
                    });
                }
            });
        }
Example #30
0
        public static Dictionary <string, object> Receive(StreamWrapper stream, CancellationToken cancellationToken,
                                                          Action <ConcurrentDictionary <string, int> > onProgressAction = null, Action <string, Exception> onErrorAction = null,
                                                          Action <int> onTotalChildrenCountKnown = null)
        {
            var account = stream.GetAccount();

            stream.BranchName = string.IsNullOrEmpty(stream.BranchName) ? "main" : stream.BranchName;

            var    client = new Client(account);
            Commit commit;

            try
            {
                if (string.IsNullOrEmpty(stream.CommitId))
                {
                    var branches   = client.StreamGetBranches(cancellationToken, stream.StreamId).Result;
                    var mainBranch = branches.FirstOrDefault(b => b.name == stream.BranchName);

                    if (mainBranch == null)
                    {
                        Log.CaptureAndThrow(new Exception("No branch found with name " + stream.BranchName));
                    }

                    if (!mainBranch.commits.items.Any())
                    {
                        throw new Exception("No commits found.");
                    }

                    commit = mainBranch.commits.items[0];
                }
                else
                {
                    commit = client.CommitGet(cancellationToken, stream.StreamId, stream.CommitId).Result;
                }
            }
            catch (Exception ex)
            {
                Utils.HandleApiExeption(ex);
                return(null);
            }

            if (commit == null)
            {
                throw new Exception("Could not get commit.");
            }

            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            var transport = new ServerTransport(account, stream.StreamId);
            var @base     = Operations.Receive(
                commit.referencedObject,
                cancellationToken,
                remoteTransport: transport,
                onProgressAction: onProgressAction,
                onErrorAction: onErrorAction,
                onTotalChildrenCountKnown: onTotalChildrenCountKnown
                ).Result;

            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            var converter = new BatchConverter();
            var data      = converter.ConvertRecursivelyToNative(@base);

            return(new Dictionary <string, object> {
                { "data", data }, { "commit", commit }
            });
        }
Example #31
0
 public void send(StreamWrapper wrapper)
 {
     // wrapper is instance of NetStream in TcpClient
     send(wrapper, true);
 }
Example #32
0
 public override void WritePacketData(StreamWrapper buff)
 {
     buff.WriteByte(WindowId);
 }
Example #33
0
        public void send(StreamWrapper wrapper, bool encapsulateBool)
        {
            var cmd = encapsulateBool ? this.encapsulate() : this;

            cmd.Write(wrapper);
        }
        private void LoadFssToken()
        {
            // Creating a new instance directly
            var client = new OAuthRequest
            {
                Method          = "GET",
                Type            = OAuthRequestType.RequestToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = serviceConfig.ConsumerKey,
                ConsumerSecret  = serviceConfig.ConsumerSecret,
                RequestUrl      = serviceConfig.ServerRoot + AcsApiClientConfig.RequestUrl,
                CallbackUrl     = serviceConfig.ServerRoot + "client"
            };


            //CookieCollection responseCookies = null;
            string setCookieHeader;
            var    fields = new Hashtable();

            using (var responseWrapper = new WebResponseWrapper(RequestToken(client)))
            {
                var responseText = GetResponseFromWebResponseWrapped(responseWrapper);

                for (var i = 0; i < responseText.Split('&').Length; i++)
                {
                    var fieldInfo = responseText.Split('&')[i].Split('=');
                    fields[fieldInfo[0]] = fieldInfo[1];
                }

                //responseCookies = responseWrapper.Get().Cookies;
                setCookieHeader = responseWrapper.Get().Headers["Set-Cookie"];
            }

            var myHttpWebRequest = Login(client, setCookieHeader, fields);

            string jsessionid;

            setCookieHeader = null;
            try
            {
                using (var responseWrapper = new WebResponseWrapper((HttpWebResponse)myHttpWebRequest.GetResponse()))
                {
                    setCookieHeader = responseWrapper.Get().Headers["Set-Cookie"];
                    var sessionCookie = responseWrapper.Get().Cookies[SessionIdKey];
                    if (sessionCookie != null)
                    {
                        jsessionid = sessionCookie.Value;

                        InvokeLog("Jsesssion found at " + jsessionid);
                        cookies.Add(sessionCookie);
                    }
                    else
                    {
                        throw new InvalidOperationException("JSession Id returned null!");
                    }
                }
            }
            catch (WebException wex)
            {
                throw new AcsApiException(AcsApiError.ServerError.ToString(), wex);
            }

            var target  = new Uri(serviceConfig.ServerRoot);
            var cdomain = target.Host;

            string[] locations;
            using (var responseWrapper = new WebResponseWrapper(ConsumerHandshake(client, jsessionid, setCookieHeader, cdomain)))
            {
                locations       = responseWrapper.Get().Headers.GetValues("location");
                setCookieHeader = responseWrapper.Get().Headers["Set-Cookie"];
            }

            if (locations == null)
            {
                throw new AcsApiException(AcsApiError.CouldNotLogin);
            }

            var myUri = new Uri(locations.FirstOrDefault() ?? string.Empty);

            InvokeLog("Request for uri" + myUri);
            if (string.IsNullOrEmpty(myUri.Query))
            {
                // No oauth_token or oauth_verifier in location header, so didn't authenticate.
                throw new AcsApiException(AcsApiError.CouldNotLogin);
            }

            var accessToken   = HttpUtility.ParseQueryString(myUri.Query).Get(OauthTokenKey);
            var oauthVerifier = HttpUtility.ParseQueryString(myUri.Query).Get(OauthVerifierKey);

            InvokeLog("Verifier response " + accessToken + " : " + oauthVerifier);

            if (string.IsNullOrEmpty(oauthVerifier))
            {
                throw new AcsApiException(AcsApiError.CouldNotFindVerifier);
            }

            using (var requestWrapper = new WebResponseWrapper(RequestFinal(client, accessToken, oauthVerifier, cdomain, setCookieHeader)))
            {
                using (var responseStream = new StreamWrapper(requestWrapper.Get().GetResponseStream()))
                {
                    if (responseStream.Get() == null)
                    {
                        throw new AcsApiException(AcsApiError.CouldNotGetAccesstoken);
                    }

                    string responseOutput;

                    // Pipes the stream to a higher level stream reader with the required encoding format.
                    using (var readStream = new StreamReader(responseStream.Get(), Encoding.UTF8))
                    {
                        responseOutput = readStream.ReadToEnd();
                    }

                    serviceConfig.AccessToken       = HttpUtility.ParseQueryString(responseOutput).Get(OauthTokenKey);
                    serviceConfig.AccessTokenSecret = HttpUtility.ParseQueryString(responseOutput).Get(OauthTokenSecretKey);

                    InvokeLog("Final Tokens: " + serviceConfig.AccessToken + " : " + serviceConfig.AccessTokenSecret);
                }
            }
        }
		protected virtual async Task HandleClientWithManualServer (TestContext ctx, CancellationToken cancellationToken)
		{
			var clientStream = new StreamWrapper (Client.Stream);

			LogDebug (ctx, 1, "HandleClientWithManualServer", Parameters.TargetHost ?? "<null>");

			await clientStream.WriteLineAsync ("Hello World!");

			var line = await clientStream.ReadLineAsync ();
			LogDebug (ctx, 1, "HandleClientWithManualServer done", line);
		}
Example #36
0
        private void WriteValue(ResourceTypeCode typeCode, object?value, BinaryWriter writer)
        {
            Debug.Assert(writer != null);

            switch (typeCode)
            {
            case ResourceTypeCode.Null:
                break;

            case ResourceTypeCode.String:
                writer.Write((string)value !);
                break;

            case ResourceTypeCode.Boolean:
                writer.Write((bool)value !);
                break;

            case ResourceTypeCode.Char:
                writer.Write((ushort)(char)value !);
                break;

            case ResourceTypeCode.Byte:
                writer.Write((byte)value !);
                break;

            case ResourceTypeCode.SByte:
                writer.Write((sbyte)value !);
                break;

            case ResourceTypeCode.Int16:
                writer.Write((short)value !);
                break;

            case ResourceTypeCode.UInt16:
                writer.Write((ushort)value !);
                break;

            case ResourceTypeCode.Int32:
                writer.Write((int)value !);
                break;

            case ResourceTypeCode.UInt32:
                writer.Write((uint)value !);
                break;

            case ResourceTypeCode.Int64:
                writer.Write((long)value !);
                break;

            case ResourceTypeCode.UInt64:
                writer.Write((ulong)value !);
                break;

            case ResourceTypeCode.Single:
                writer.Write((float)value !);
                break;

            case ResourceTypeCode.Double:
                writer.Write((double)value !);
                break;

            case ResourceTypeCode.Decimal:
                writer.Write((decimal)value !);
                break;

            case ResourceTypeCode.DateTime:
                // Use DateTime's ToBinary & FromBinary.
                long data = ((DateTime)value !).ToBinary();
                writer.Write(data);
                break;

            case ResourceTypeCode.TimeSpan:
                writer.Write(((TimeSpan)value !).Ticks);
                break;

            // Special Types
            case ResourceTypeCode.ByteArray:
            {
                byte[] bytes = (byte[])value !;
                writer.Write(bytes.Length);
                writer.Write(bytes, 0, bytes.Length);
                break;
            }

            case ResourceTypeCode.Stream:
            {
                StreamWrapper sw = (StreamWrapper)value !;
                if (sw.Stream.GetType() == typeof(MemoryStream))
                {
                    MemoryStream ms = (MemoryStream)sw.Stream;
                    if (ms.Length > int.MaxValue)
                    {
                        throw new ArgumentException(SR.ArgumentOutOfRange_StreamLength);
                    }
                    byte[] arr = ms.ToArray();
                    writer.Write(arr.Length);
                    writer.Write(arr, 0, arr.Length);
                }
                else
                {
                    Stream s = sw.Stream;
                    // we've already verified that the Stream is seekable
                    if (s.Length > int.MaxValue)
                    {
                        throw new ArgumentException(SR.ArgumentOutOfRange_StreamLength);
                    }

                    s.Position = 0;
                    writer.Write((int)s.Length);
                    byte[] buffer = new byte[4096];
                    int    read   = 0;
                    while ((read = s.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        writer.Write(buffer, 0, read);
                    }
                    if (sw.CloseAfterWrite)
                    {
                        s.Close();
                    }
                }
                break;
            }

            default:
                Debug.Assert(typeCode >= ResourceTypeCode.StartOfUserTypes, $"ResourceReader: Unsupported ResourceTypeCode in .resources file!  {typeCode}");
                throw new PlatformNotSupportedException(SR.NotSupported_BinarySerializedResources);
            }
        }
		protected virtual async Task HandleServerWithManualClient (TestContext ctx, CancellationToken cancellationToken)
		{
			LogDebug (ctx, 1, "HandleServerWithManualClient");

			var serverStream = new StreamWrapper (Server.Stream);
			await serverStream.WriteLineAsync ("Hello World!");

			LogDebug (ctx, 1, "HandleServerWithManualClient reading");

			var line = await serverStream.ReadLineAsync ();
			LogDebug (ctx, 1, "HandleServerWithManualClient done", line);
		}
Example #38
0
        public void Generate()
        {
            BinaryWriter writer;
            IFormatter   formatter;

            if (resources == null)
            {
                throw new InvalidOperationException("The resource writer has already been closed and cannot be edited");
            }

            writer    = new BinaryWriter(stream, Encoding.UTF8);
            formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File | StreamingContextStates.Persistence));

            /* The ResourceManager header */

            writer.Write(ResourceManager.MagicNumber);
            writer.Write(ResourceManager.HeaderVersionNumber);

            /* Build the rest of the ResourceManager
             * header in memory, because we need to know
             * how long it is in advance
             */
            MemoryStream resman_stream = new MemoryStream();
            BinaryWriter resman        = new BinaryWriter(resman_stream,
                                                          Encoding.UTF8);

            string type_name = null;

            if (type_name_converter != null)
            {
                type_name = type_name_converter(typeof(ResourceReader));
            }
            if (type_name == null)
            {
                type_name = typeof(ResourceReader).AssemblyQualifiedName;
            }

            resman.Write(type_name);
            resman.Write(typeof(RuntimeResourceSet).FullName);

            /* Only space for 32 bits of header len in the
             * resource file format
             */
            int resman_len = (int)resman_stream.Length;

            writer.Write(resman_len);
            writer.Write(resman_stream.GetBuffer(), 0, resman_len);

            /* We need to build the ResourceReader name
             * and data sections simultaneously
             */
            MemoryStream res_name_stream = new MemoryStream();
            BinaryWriter res_name        = new BinaryWriter(res_name_stream, Encoding.Unicode);

            MemoryStream res_data_stream = new MemoryStream();
            BinaryWriter res_data        = new BinaryWriter(res_data_stream,
                                                            Encoding.UTF8);

            /* Not sure if this is the best collection to
             * use, I just want an unordered list of
             * objects with fast lookup, but without
             * needing a key.  (I suppose a hashtable with
             * key==value would work, but I need to find
             * the index of each item later)
             */
            ArrayList types = new ArrayList();

            int [] hashes       = new int [resources.Count];
            int [] name_offsets = new int [resources.Count];
            int    count        = 0;

            IDictionaryEnumerator res_enum = resources.GetEnumerator();

            while (res_enum.MoveNext())
            {
                /* Hash the name */
                hashes [count] = GetHash((string)res_enum.Key);

                /* Record the offsets */
                name_offsets [count] = (int)res_name.BaseStream.Position;

                /* Write the name section */
                res_name.Write((string)res_enum.Key);
                res_name.Write((int)res_data.BaseStream.Position);

                if (res_enum.Value == null)
                {
                    Write7BitEncodedInt(res_data, -1);
                    count++;
                    continue;
                }
                // implementation note: TypeByNameObject is
                // not used in 1.x profile.
                TypeByNameObject tbn     = res_enum.Value as TypeByNameObject;
                Type             type    = tbn != null ? null : res_enum.Value.GetType();
                object           typeObj = tbn != null ? (object)tbn.TypeName : type;

                /* Keep a list of unique types */
                // do not output predefined ones.
                switch ((type != null && !type.IsEnum) ? Type.GetTypeCode(type) : TypeCode.Empty)
                {
                case TypeCode.Decimal:
                case TypeCode.Single:
                case TypeCode.Double:
                case TypeCode.SByte:
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                case TypeCode.Byte:
                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                case TypeCode.DateTime:
                case TypeCode.String:
                    break;

                default:
                    if (type == typeof(TimeSpan))
                    {
                        break;
                    }
                    if (type == typeof(MemoryStream))
                    {
                        break;
                    }
                    if (type == typeof(StreamWrapper))
                    {
                        break;
                    }
                    if (type == typeof(byte[]))
                    {
                        break;
                    }

                    if (!types.Contains(typeObj))
                    {
                        types.Add(typeObj);
                    }
                    /* Write the data section */
                    Write7BitEncodedInt(res_data, (int)PredefinedResourceType.FistCustom + types.IndexOf(typeObj));
                    break;
                }

                /* Strangely, Char is serialized
                 * rather than just written out
                 */
                if (tbn != null)
                {
                    res_data.Write((byte [])tbn.Value);
                }
                else if (type == typeof(Byte))
                {
                    res_data.Write((byte)PredefinedResourceType.Byte);
                    res_data.Write((Byte)res_enum.Value);
                }
                else if (type == typeof(Decimal))
                {
                    res_data.Write((byte)PredefinedResourceType.Decimal);
                    res_data.Write((Decimal)res_enum.Value);
                }
                else if (type == typeof(DateTime))
                {
                    res_data.Write((byte)PredefinedResourceType.DateTime);
                    res_data.Write(((DateTime)res_enum.Value).Ticks);
                }
                else if (type == typeof(Double))
                {
                    res_data.Write((byte)PredefinedResourceType.Double);
                    res_data.Write((Double)res_enum.Value);
                }
                else if (type == typeof(Int16))
                {
                    res_data.Write((byte)PredefinedResourceType.Int16);
                    res_data.Write((Int16)res_enum.Value);
                }
                else if (type == typeof(Int32))
                {
                    res_data.Write((byte)PredefinedResourceType.Int32);
                    res_data.Write((Int32)res_enum.Value);
                }
                else if (type == typeof(Int64))
                {
                    res_data.Write((byte)PredefinedResourceType.Int64);
                    res_data.Write((Int64)res_enum.Value);
                }
                else if (type == typeof(SByte))
                {
                    res_data.Write((byte)PredefinedResourceType.SByte);
                    res_data.Write((SByte)res_enum.Value);
                }
                else if (type == typeof(Single))
                {
                    res_data.Write((byte)PredefinedResourceType.Single);
                    res_data.Write((Single)res_enum.Value);
                }
                else if (type == typeof(String))
                {
                    res_data.Write((byte)PredefinedResourceType.String);
                    res_data.Write((String)res_enum.Value);
                }
                else if (type == typeof(TimeSpan))
                {
                    res_data.Write((byte)PredefinedResourceType.TimeSpan);
                    res_data.Write(((TimeSpan)res_enum.Value).Ticks);
                }
                else if (type == typeof(UInt16))
                {
                    res_data.Write((byte)PredefinedResourceType.UInt16);
                    res_data.Write((UInt16)res_enum.Value);
                }
                else if (type == typeof(UInt32))
                {
                    res_data.Write((byte)PredefinedResourceType.UInt32);
                    res_data.Write((UInt32)res_enum.Value);
                }
                else if (type == typeof(UInt64))
                {
                    res_data.Write((byte)PredefinedResourceType.UInt64);
                    res_data.Write((UInt64)res_enum.Value);
                }
                else if (type == typeof(byte[]))
                {
                    res_data.Write((byte)PredefinedResourceType.ByteArray);
                    byte [] data = (byte[])res_enum.Value;
                    res_data.Write((uint)data.Length);
                    res_data.Write(data, 0, data.Length);
                }
                else if (type == typeof(MemoryStream))
                {
                    res_data.Write((byte)PredefinedResourceType.Stream);
                    byte [] data = ((MemoryStream)res_enum.Value).ToArray();
                    res_data.Write((uint)data.Length);
                    res_data.Write(data, 0, data.Length);
                }
                else if (type == typeof(StreamWrapper))
                {
                    StreamWrapper sw = (StreamWrapper)res_enum.Value;
                    sw.Stream.Position = 0;

                    res_data.Write((byte)PredefinedResourceType.Stream);
                    byte [] data = ReadStream(sw.Stream);
                    res_data.Write((uint)data.Length);
                    res_data.Write(data, 0, data.Length);

                    if (sw.CloseAfterWrite)
                    {
                        sw.Stream.Close();
                    }
                }
                else
                {
                    /* non-intrinsic types are
                     * serialized
                     */
                    formatter.Serialize(res_data.BaseStream, res_enum.Value);
                }
                count++;
            }

            /* Sort the hashes, keep the name offsets
             * matching up
             */
            Array.Sort(hashes, name_offsets);

            /* now do the ResourceReader header */

            writer.Write(2);
            writer.Write(resources.Count);
            writer.Write(types.Count);

            /* Write all of the unique types */
            foreach (object type in types)
            {
                if (type is Type)
                {
                    writer.Write(((Type)type).AssemblyQualifiedName);
                }
                else
                {
                    writer.Write((string)type);
                }
            }

            /* Pad the next fields (hash values) on an 8
             * byte boundary, using the letters "PAD"
             */
            int pad_align = (int)(writer.BaseStream.Position & 7);
            int pad_chars = 0;

            if (pad_align != 0)
            {
                pad_chars = 8 - pad_align;
            }

            for (int i = 0; i < pad_chars; i++)
            {
                writer.Write((byte)"PAD" [i % 3]);
            }

            /* Write the hashes */
            for (int i = 0; i < resources.Count; i++)
            {
                writer.Write(hashes[i]);
            }

            /* and the name offsets */
            for (int i = 0; i < resources.Count; i++)
            {
                writer.Write(name_offsets [i]);
            }

            /* Write the data section offset */
            int data_offset = (int)writer.BaseStream.Position +
                              (int)res_name_stream.Length + 4;

            writer.Write(data_offset);

            /* The name section goes next */
            writer.Write(res_name_stream.GetBuffer(), 0,
                         (int)res_name_stream.Length);
            /* The data section is last */
            writer.Write(res_data_stream.GetBuffer(), 0,
                         (int)res_data_stream.Length);

            res_name.Close();
            res_data.Close();

            /* Don't close writer, according to the spec */
            writer.Flush();

            // ResourceWriter is no longer editable
            resources = null;
        }
Example #39
0
        /// <summary>
        /// This method is used to upload a CSV file in ZIP format for Bulk Write API. The response contains the file_id.
        /// Use this ID while making the Bulk Write request.
        /// </summary>
        /// <param name="orgID">The unique ID (zgid) of your organization obtained through the Organization API.</param>
        /// <param name="absoluteFilePath">The absoluteFilePath of the zip file you want to upload.</param>
        public static void UploadFile(string orgID, string absoluteFilePath)
        {
            //example
            //string absoluteFilePath = "/Users/user_name/Documents/Leads.zip";
            //string orgID = "6xxxx";

            //Get instance of BulkWriteOperations Class
            BulkWriteOperations bulkWriteOperations = new BulkWriteOperations();

            //Get instance of FileBodyWrapper class that will contain the request file
            FileBodyWrapper fileBodyWrapper = new FileBodyWrapper();

            //Get instance of StreamWrapper class that takes absolute path of the file to be attached as parameter
            StreamWrapper streamWrapper = new StreamWrapper(absoluteFilePath);

            //FileInfo fileInfo = new FileInfo(absoluteFilePath);

            //Get instance of StreamWrapper class that takes file name and stream of the file to be attached as parameter
            //StreamWrapper streamWrapper = new StreamWrapper(fileInfo.Name, fileInfo.OpenRead());

            //Set file to the FileBodyWrapper instance
            fileBodyWrapper.File = streamWrapper;

            //Get instance of HeaderMap Class
            HeaderMap headerInstance = new HeaderMap();

            //To indicate that this a Bulk Write operation
            headerInstance.Add(UploadFileHeader.FEATURE, "bulk-write");

            headerInstance.Add(UploadFileHeader.X_CRM_ORG, orgID);

            //Call uploadFile method that takes FileBodyWrapper instance and headerInstance as parameter
            APIResponse <ActionResponse> response = bulkWriteOperations.UploadFile(fileBodyWrapper, headerInstance);

            if (response != null)
            {
                //Get the status code from response
                Console.WriteLine("Status Code: " + response.StatusCode);

                //Check if expected response is received
                if (response.IsExpected)
                {
                    //Get object from response
                    ActionResponse actionResponse = response.Object;

                    //Check if the request is successful
                    if (actionResponse is SuccessResponse)
                    {
                        //Get the received SuccessResponse instance
                        SuccessResponse successResponse = (SuccessResponse)actionResponse;

                        //Get the Status
                        Console.WriteLine("Status: " + successResponse.Status.Value);

                        //Get the Code
                        Console.WriteLine("Code: " + successResponse.Code.Value);

                        Console.WriteLine("Details: ");

                        //Get the details map
                        foreach (KeyValuePair <string, object> entry in successResponse.Details)
                        {
                            //Get each value in the map
                            Console.WriteLine(entry.Key + " : " + JsonConvert.SerializeObject(entry.Value));
                        }

                        //Get the Message
                        Console.WriteLine("Message: " + successResponse.Message.Value);
                    }
                    //Check if the request returned an exception
                    else if (actionResponse is APIException)
                    {
                        //Get the received APIException instance
                        APIException exception = (APIException)actionResponse;

                        if (exception.Status != null)
                        {
                            //Get the Status
                            Console.WriteLine("Status: " + exception.Status.Value);
                        }

                        if (exception.Code != null)
                        {
                            //Get the Code
                            Console.WriteLine("Code: " + exception.Code.Value);
                        }

                        if (exception.Message != null)
                        {
                            //Get the Message
                            Console.WriteLine("Message: " + exception.Message.Value);
                        }

                        Console.WriteLine("Details: ");

                        if (exception.Details != null)
                        {
                            //Get the details map
                            foreach (KeyValuePair <string, object> entry in exception.Details)
                            {
                                //Get each value in the map
                                Console.WriteLine(entry.Key + ": " + JsonConvert.SerializeObject(entry.Value));
                            }
                        }

                        if (exception.ErrorMessage != null)
                        {
                            //Get the ErrorMessage
                            Console.WriteLine("ErrorMessage: " + exception.ErrorMessage.Value);
                        }

                        //Get the ErrorCode
                        Console.WriteLine("ErrorCode: " + exception.ErrorCode);

                        if (exception.XError != null)
                        {
                            //Get the XError
                            Console.WriteLine("XError: " + exception.XError.Value);
                        }

                        if (exception.Info != null)
                        {
                            //Get the Info
                            Console.WriteLine("Info: " + exception.Info.Value);
                        }

                        if (exception.XInfo != null)
                        {
                            //Get the XInfo
                            Console.WriteLine("XInfo: " + exception.XInfo.Value);
                        }

                        //Get the HttpStatus
                        Console.WriteLine("HttpStatus: " + exception.HttpStatus);
                    }
                }
                else
                { //If response is not as expected
                    //Get model object from response
                    Model responseObject = response.Model;

                    //Get the response object's class
                    Type type = responseObject.GetType();

                    //Get all declared fields of the response class
                    Console.WriteLine("Type is: {0}", type.Name);

                    PropertyInfo[] props = type.GetProperties();

                    Console.WriteLine("Properties (N = {0}):", props.Length);

                    foreach (var prop in props)
                    {
                        if (prop.GetIndexParameters().Length == 0)
                        {
                            Console.WriteLine("{0} ({1}) : {2}", prop.Name, prop.PropertyType.Name, prop.GetValue(responseObject));
                        }
                        else
                        {
                            Console.WriteLine("{0} ({1}) : <Indexed>", prop.Name, prop.PropertyType.Name);
                        }
                    }
                }
            }
        }
Example #40
0
        private IEnumerable<BytesWraper> ReceiveMessageBodyZip(int contentLength)
        {
            var bytesWraper = new BytesWraper();
            var streamWrapper = new StreamWrapper(
                _request.ClientStream, _receiverHelper);

            using (Stream stream = GetZipStream(streamWrapper))
            {
                int bufferSize = _request.TcpClient.ReceiveBufferSize;
                byte[] buffer = new byte[bufferSize];

                bytesWraper.Value = buffer;

                while (true)
                {
                    int bytesRead = stream.Read(buffer, 0, bufferSize);

                    if (bytesRead == 0)
                    {
                        if (streamWrapper.TotalBytesRead == contentLength)
                        {
                            yield break;
                        }
                        else
                        {
                            WaitData();

                            continue;
                        }
                    }

                    bytesWraper.Length = bytesRead;
                    yield return bytesWraper;
                }
            }
        }
        public void SerializeBody(IXBody body, Stream stream)
        {
            var comStr = new StreamWrapper(stream);

            ((SwBody)body).Body.Save(comStr);
        }
Example #42
0
        // Приём сжатых данных.
        private IEnumerable<BytesWraper> GetMessageBodySourceZip()
        {
            if (_headers.ContainsKey("Transfer-Encoding"))
            {
                return ReceiveMessageBodyChunkedZip();
            }

            if (ContentLength != -1)
            {
                return ReceiveMessageBodyZip(ContentLength);
            }

            bool isHtml;

            if (ContentType.Equals("text/html", StringComparison.OrdinalIgnoreCase))
            {
                isHtml = true;
            }
            else
            {
                isHtml = false;
            }

            var streamWrapper = new StreamWrapper(
                _request.ClientStream, _receiverHelper);

            return ReceiveMessageBody(GetZipStream(streamWrapper), isHtml);
        }
        public static void GetFile(PortableDeviceFile file, out StreamWrapper outputStream)
        {

            gopro.DownloadFile(file, out outputStream);

            //outputStream.Flush();
            //outputStream.Close();
        }
Example #44
0
    private void HandleMetaFileUpload()
    {
        string       message = string.Empty;
        MetaFileInfo mfi     = null;

        try
        {
            // Check the allowed extensions
            CheckAllowedExtensions();

            if (InsertMode)
            {
                // Create new meta file
                mfi = new MetaFileInfo(FileUploadControl.PostedFile, ObjectID, ObjectType, Category);
                mfi.MetaFileSiteID = SiteID;
            }
            else
            {
                if (MetaFileID > 0)
                {
                    mfi = MetaFileInfoProvider.GetMetaFileInfo(MetaFileID);
                }
                else
                {
                    DataSet ds = MetaFileInfoProvider.GetMetaFilesWithoutBinary(ObjectID, ObjectType, Category, null, null);
                    if (!DataHelper.DataSourceIsEmpty(ds))
                    {
                        mfi = new MetaFileInfo(ds.Tables[0].Rows[0]);
                    }
                }

                if (mfi != null)
                {
                    string fileExt = Path.GetExtension(FileUploadControl.FileName);
                    // Init the MetaFile data
                    mfi.MetaFileName      = URLHelper.GetSafeFileName(FileUploadControl.FileName, null);
                    mfi.MetaFileExtension = fileExt;

                    mfi.MetaFileSize     = Convert.ToInt32(FileUploadControl.PostedFile.InputStream.Length);
                    mfi.MetaFileMimeType = MimeTypeHelper.GetMimetype(fileExt);
                    mfi.InputStream      = StreamWrapper.New(FileUploadControl.PostedFile.InputStream);

                    // Set image properties
                    if (ImageHelper.IsImage(mfi.MetaFileExtension))
                    {
                        // Make MetaFile binary load from InputStream
                        mfi.MetaFileBinary = null;
                        ImageHelper ih = new ImageHelper(mfi.MetaFileBinary);
                        mfi.MetaFileImageHeight = ih.ImageHeight;
                        mfi.MetaFileImageWidth  = ih.ImageWidth;
                    }
                }
            }

            if (mfi != null)
            {
                // Save file to the database
                MetaFileInfoProvider.SetMetaFileInfo(mfi);
            }
        }
        catch (Exception ex)
        {
            // Log the exception
            EventLogProvider.LogException("Uploader", "UploadMetaFile", ex);

            message = ex.Message;
        }
        finally
        {
            string afterSaveScript = string.Empty;
            if (String.IsNullOrEmpty(message))
            {
                if (!string.IsNullOrEmpty(AfterSaveJavascript))
                {
                    afterSaveScript = String.Format(@"
                        if (window.{0} != null) {{
                            window.{0}()
                        }} else if ((window.parent != null) && (window.parent.{0} != null)) {{
                            window.parent.{0}() 
                        }}", AfterSaveJavascript);
                }
                else
                {
                    afterSaveScript = String.Format(@"
                        if ((window.parent != null) && (/parentelemid={0}/i.test(window.location.href)) && (window.parent.InitRefresh_{0}))
                        {{
                            window.parent.InitRefresh_{0}('{1}', false, false, {2});
                        }}
                        else {{ 
                            if ('{1}' != '') {{
                                alert('{1}');
                            }}
                        }}", ParentElemID, ScriptHelper.GetString(message.Trim(), false), mfi.MetaFileID.ToString() + (InsertMode ? ",'insert'" : ",'update'"));
                }
            }
            else
            {
                afterSaveScript += ScriptHelper.GetAlertScript(message, false);
            }

            ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, afterSaveScript, true);
        }
    }
Example #45
0
		/// <summary>
		/// PhpStream is created by a StreamWrapper together with the
		/// encapsulated RawStream (the actual file opening is handled 
		/// by the wrapper).
		/// </summary>
		/// <remarks>
		/// This class newly implements the auto-remove behavior too
		/// (see <see cref="StreamAccessOptions.Temporary"/>).
		/// </remarks>
		/// <param name="openingWrapper">The parent instance.</param>
		/// <param name="accessOptions">The additional options parsed from the <c>fopen()</c> mode.</param>
		/// <param name="openedPath">The absolute path to the opened resource.</param>
		/// <param name="context">The stream context passed to fopen().</param>
		public PhpStream(StreamWrapper openingWrapper, StreamAccessOptions accessOptions, string openedPath, StreamContext context)
			: base(PhpStreamTypeName)
		{
			Debug.Assert(context != null);

			this.context = context;
			this.Wrapper = openingWrapper;
			this.OpenedPath = openedPath;

			// Stream modifiers (defined in open-time).
			this.Options = accessOptions;

			// Allocate the text conversion filters for this stream.
			if ((accessOptions & StreamAccessOptions.UseText) > 0)
			{
				if ((accessOptions & StreamAccessOptions.Read) > 0)
				{
					textReadFilter = new TextReadFilter();
				}
				if ((accessOptions & StreamAccessOptions.Write) > 0)
				{
					textWriteFilter = new TextWriteFilter();
				}
			}

			this.readTimeout = ScriptContext.CurrentContext.Config.FileSystem.DefaultSocketTimeout;
		}
Example #46
0
		public NativeStream(Stream nativeStream, StreamWrapper openingWrapper, StreamAccessOptions accessOptions, string openedPath, StreamContext context)
			: base(openingWrapper, accessOptions, openedPath, context)
		{
			Debug.Assert(nativeStream != null);
			this.stream = nativeStream;
		}
Example #47
0
 public override void ReadPacketData(StreamWrapper buff)
 {
     Slot = buff.ReadByte();
 }
Example #48
0
		async Task<Stream> GetStreamFromCacheAsync(Uri uri, CancellationToken cancellationToken)
		{
			string key = GetCacheKey(uri);
			LockingSemaphore sem;
			lock (s_syncHandle)
			{
				if (s_semaphores.ContainsKey(key))
					sem = s_semaphores[key];
				else
					s_semaphores.Add(key, sem = new LockingSemaphore(1));
			}

			try
			{
				await sem.WaitAsync(cancellationToken);
				Stream stream = await GetStreamAsyncUnchecked(key, uri, cancellationToken);
				if (stream == null)
				{
					sem.Release();
					return null;
				}
				var wrapped = new StreamWrapper(stream);
				wrapped.Disposed += (o, e) => sem.Release();
				return wrapped;
			}
			catch (OperationCanceledException)
			{
				sem.Release();
				throw;
			}
		}
Example #49
0
 public override void WritePacketData(StreamWrapper buff)
 {
     buff.WriteShort(Slot);
 }
Example #50
0
 /// <summary>
 /// Stat the path coming from ResolvePath (file:// wrapper expects path w/o the scheme).
 /// </summary>
 /// <param name="path"></param>
 /// <param name="url"></param>
 /// <param name="wrapper"></param>
 /// <param name="quiet"></param>
 /// <returns>True if stat was successfuly added into cache.</returns>
 private static bool StatInternalStat(string path, string url, StreamWrapper wrapper, bool quiet)
 {
     StatStruct stat = wrapper.Stat(path, quiet ? StreamStatOptions.Quiet : StreamStatOptions.Empty, StreamContext.Default, false);
     if (stat.st_size >= 0)
     {
         statCacheUrl = url;
         statCache = stat;
         return true;
     }
     else
         return false;
 }
Example #51
0
        private void WriteValue(ResourceTypeCode typeCode, Object value, BinaryWriter writer)
#endif // FEATURE_SERIALIZATION
        {
            Contract.Requires(writer != null);

            switch (typeCode)
            {
            case ResourceTypeCode.Null:
                break;

            case ResourceTypeCode.String:
                writer.Write((String)value);
                break;

            case ResourceTypeCode.Boolean:
                writer.Write((bool)value);
                break;

            case ResourceTypeCode.Char:
                writer.Write((UInt16)(char)value);
                break;

            case ResourceTypeCode.Byte:
                writer.Write((byte)value);
                break;

            case ResourceTypeCode.SByte:
                writer.Write((sbyte)value);
                break;

            case ResourceTypeCode.Int16:
                writer.Write((Int16)value);
                break;

            case ResourceTypeCode.UInt16:
                writer.Write((UInt16)value);
                break;

            case ResourceTypeCode.Int32:
                writer.Write((Int32)value);
                break;

            case ResourceTypeCode.UInt32:
                writer.Write((UInt32)value);
                break;

            case ResourceTypeCode.Int64:
                writer.Write((Int64)value);
                break;

            case ResourceTypeCode.UInt64:
                writer.Write((UInt64)value);
                break;

            case ResourceTypeCode.Single:
                writer.Write((Single)value);
                break;

            case ResourceTypeCode.Double:
                writer.Write((Double)value);
                break;

            case ResourceTypeCode.Decimal:
                writer.Write((Decimal)value);
                break;

            case ResourceTypeCode.DateTime:
                // Use DateTime's ToBinary & FromBinary.
                Int64 data = ((DateTime)value).ToBinary();
                writer.Write(data);
                break;

            case ResourceTypeCode.TimeSpan:
                writer.Write(((TimeSpan)value).Ticks);
                break;

            // Special Types
            case ResourceTypeCode.ByteArray:
            {
                byte[] bytes = (byte[])value;
                writer.Write(bytes.Length);
                writer.Write(bytes, 0, bytes.Length);
                break;
            }

            case ResourceTypeCode.Stream:
            {
                StreamWrapper sw = (StreamWrapper)value;
                if (sw.m_stream.GetType() == typeof(MemoryStream))
                {
                    MemoryStream ms = (MemoryStream)sw.m_stream;
                    if (ms.Length > Int32.MaxValue)
                    {
                        throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
                    }
                    int offset, len;
                    ms.InternalGetOriginAndLength(out offset, out len);
                    byte[] bytes = ms.InternalGetBuffer();
                    writer.Write(len);
                    writer.Write(bytes, offset, len);
                }
                else
                {
                    Stream s = sw.m_stream;
                    // we've already verified that the Stream is seekable
                    if (s.Length > Int32.MaxValue)
                    {
                        throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
                    }

                    s.Position = 0;
                    writer.Write((int)s.Length);
                    byte[] buffer = new byte[_DefaultBufferSize];
                    int    read   = 0;
                    while ((read = s.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        writer.Write(buffer, 0, read);
                    }
                    if (sw.m_closeAfterWrite)
                    {
                        s.Close();
                    }
                }
                break;
            }

            default:
                Contract.Assert(typeCode >= ResourceTypeCode.StartOfUserTypes, String.Format(CultureInfo.InvariantCulture, "ResourceReader: Unsupported ResourceTypeCode in .resources file!  {0}", typeCode));
#if FEATURE_SERIALIZATION
                objFormatter.Serialize(writer.BaseStream, value);
                break;
#else
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization"));
#endif // FEATURE_SERIALIZATION
            }
        }
Example #52
0
    /// <summary>
    /// Opens the specified file using the appropriate preview handler and displays the result in PreviewHandlerHost.
    /// </summary>
    /// <param name="filename"></param>
    /// <returns></returns>
    public bool Open(string filename)
    {
        UnloadPreviewHandler();

        if (String.IsNullOrEmpty(filename))
        {
            ErrorMessage = "No file loaded.";
            return(false);
        }

        // try to get GUID for the preview handler
        Guid guid = GetPreviewHandlerGUID(filename);

        ErrorMessage = "";

        if (guid != Guid.Empty)
        {
            try
            {
                if (guid != mCurrentPreviewHandlerGUID)
                {
                    mCurrentPreviewHandlerGUID = guid;

                    // need to instantiate a different COM type (file format has changed)
                    if (mCurrentPreviewHandler != null)
                    {
                        Marshal.FinalReleaseComObject(mCurrentPreviewHandler);
                    }

                    // use reflection to instantiate the preview handler type
                    Type comType = Type.GetTypeFromCLSID(mCurrentPreviewHandlerGUID);
                    mCurrentPreviewHandler = Activator.CreateInstance(comType);
                }

                if (mCurrentPreviewHandler is IInitializeWithFile)
                {
                    // some handlers accept a filename
                    ((IInitializeWithFile)mCurrentPreviewHandler).Initialize(filename, 0);
                }
                else if (mCurrentPreviewHandler is IInitializeWithStream)
                {
                    if (File.Exists(filename))
                    {
                        // other handlers want an IStream (in case, a file stream)
                        mCurrentPreviewHandlerStream = File.Open(filename, FileMode.Open);
                        StreamWrapper stream = new StreamWrapper(mCurrentPreviewHandlerStream);
                        ((IInitializeWithStream)mCurrentPreviewHandler).Initialize(stream, 0);
                    }
                    else
                    {
                        ErrorMessage = "File not found.";
                    }
                }
                else if (mCurrentPreviewHandler is IInitializeWithItem)
                {
                    // a third category exists, must be initialised with a shell item
                    IShellItem shellItem;
                    SHCreateItemFromParsingName(filename, IntPtr.Zero, new Guid(GUID_ISHELLITEM), out shellItem);
                    ((IInitializeWithItem)mCurrentPreviewHandler).Initialize(shellItem, 0);
                }

                if (mCurrentPreviewHandler is IPreviewHandler)
                {
                    // bind the preview handler to the control's bounds and preview the content
                    Rectangle r = ClientRectangle;
                    ((IPreviewHandler)mCurrentPreviewHandler).SetWindow(Handle, ref r);
                    ((IPreviewHandler)mCurrentPreviewHandler).DoPreview();

                    return(true);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "Preview could not be generated.\n" + ex.Message;
            }
        }
        else
        {
            ErrorMessage = "No preview available.";
        }

        return(false);
    }
Example #53
0
    /// <summary>
    /// Opens the specified stream using the preview handler COM type with the provided GUID and displays the result in PreviewHandlerHost.
    /// </summary>
    /// <param name="stream"></param>
    /// <param name="previewHandler"></param>
    /// <returns></returns>
    public bool Open(Stream stream, Guid previewHandler)
    {
        UnloadPreviewHandler();

        if (stream == null)
        {
            ErrorMessage = "No file loaded.";
            return(false);
        }

        ErrorMessage = "";

        if (previewHandler != Guid.Empty)
        {
            try
            {
                if (previewHandler != mCurrentPreviewHandlerGUID)
                {
                    mCurrentPreviewHandlerGUID = previewHandler;

                    // need to instantiate a different COM type (file format has changed)
                    if (mCurrentPreviewHandler != null)
                    {
                        Marshal.FinalReleaseComObject(mCurrentPreviewHandler);
                    }

                    // use reflection to instantiate the preview handler type
                    Type comType = Type.GetTypeFromCLSID(mCurrentPreviewHandlerGUID);
                    mCurrentPreviewHandler = Activator.CreateInstance(comType);
                }

                if (mCurrentPreviewHandler is IInitializeWithStream)
                {
                    // must wrap the stream to provide compatibility with IStream
                    mCurrentPreviewHandlerStream = stream;
                    StreamWrapper wrapped = new StreamWrapper(mCurrentPreviewHandlerStream);
                    ((IInitializeWithStream)mCurrentPreviewHandler).Initialize(wrapped, 0);
                }

                if (mCurrentPreviewHandler is IPreviewHandler)
                {
                    // bind the preview handler to the control's bounds and preview the content
                    Rectangle r = ClientRectangle;
                    ((IPreviewHandler)mCurrentPreviewHandler).SetWindow(Handle, ref r);
                    ((IPreviewHandler)mCurrentPreviewHandler).DoPreview();

                    return(true);
                }
            }
            catch (Exception ex)
            {
                ErrorMessage = "Preview could not be generated.\n" + ex.Message;
            }
        }
        else
        {
            ErrorMessage = "No preview available.";
        }

        return(false);
    }
Example #54
0
		/// <summary>
		/// Merges the path with the current working directory
		/// to get a canonicalized absolute pathname representing the same file.
		/// </summary>
		/// <remarks>
		/// This method is an analogy of <c>main/safe_mode.c: php_checkuid</c>.
		/// Looks for the file in the <c>include_path</c> and checks for <c>open_basedir</c> restrictions.
		/// </remarks>
		/// <param name="path">An absolute or relative path to a file.</param>
		/// <param name="wrapper">The wrapper found for the specified file or <c>null</c> if the path resolution fails.</param>
		/// <param name="mode">The checking mode of the <see cref="CheckAccess"/> method (file, directory etc.).</param>
		/// <param name="options">Additional options for the <see cref="CheckAccess"/> method.</param>
		/// <returns><c>true</c> if all the resolution and checking passed without an error, <b>false</b> otherwise.</returns>
		/// <exception cref="PhpException">Security violation - when the target file 
		/// lays outside the tree defined by <c>open_basedir</c> configuration option.</exception>
		public static bool ResolvePath(ref string path, out StreamWrapper wrapper, CheckAccessMode mode, CheckAccessOptions options)
		{
			// Path will contain the absolute path without file:// or the complete URL; filename is the relative path.
			string filename, scheme = GetSchemeInternal(path, out filename);
			wrapper = StreamWrapper.GetWrapper(scheme, (StreamOptions)options);
			if (wrapper == null) return false;

			if (wrapper.IsUrl)
			{
				// Note: path contains the whole URL, filename the same without the scheme:// portion.
				// What to check more?
			}
			else if (scheme != "php")
			{
				try
				{
					// Filename contains the original path without the scheme:// portion, check for include path.
					bool isInclude = false;
					if ((options & CheckAccessOptions.UseIncludePath) > 0)
					{
						isInclude = CheckIncludePath(filename, ref path);
					}

					// Path will now contain an absolute path (either to an include or actual directory).
					if (!isInclude)
					{
						path = Path.GetFullPath(Path.Combine(ScriptContext.CurrentContext.WorkingDirectory, filename));
					}
				}
				catch (Exception)
				{
                    if ((options & CheckAccessOptions.Quiet) == 0)
					PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_filename_invalid",
						FileSystemUtils.StripPassword(path)));
					return false;
				}

				GlobalConfiguration global_config = Configuration.Global;

				// Note: extensions check open_basedir too -> double check..
				if (!global_config.SafeMode.IsPathAllowed(path))
				{
					if ((options & CheckAccessOptions.Quiet) == 0)
						PhpException.Throw(PhpError.Warning, CoreResources.GetString("open_basedir_effect",
							path, global_config.SafeMode.GetAllowedPathPrefixesJoin()));
					return false;
				}

				// Replace all '/' with '\'.
				// path = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);

                if (Environment.OSVersion.Platform != PlatformID.Unix)
                {
                    Debug.Assert(
                        path.IndexOf(Path.AltDirectorySeparatorChar) == -1 ||
                        (Path.AltDirectorySeparatorChar == Path.DirectorySeparatorChar),    // on Mono, so ignore it
                        string.Format("'{0}' should not contain '{1}' char.", path, Path.AltDirectorySeparatorChar));
                }

				// The file wrapper expects an absolute path w/o the scheme, others expect the scheme://url.
				if (scheme != "file")
				{
					path = String.Format("{0}://{1}", scheme, path);
				}
			}

			return true;
		}
		async Task RunWithManualServer (TestContext ctx, CancellationToken cancellationToken)
		{
			var clientStream = new StreamWrapper (Client.Stream);

			ctx.LogMessage ("WRITING REQUEST: {0}", Parameters.ClientParameters.TargetHost ?? "<null>");

			await clientStream.WriteLineAsync ("GET / HTTP/1.0");
			try {
				if (Parameters.ClientParameters.TargetHost != null)
					await clientStream.WriteLineAsync (string.Format ("Host: {0}", Parameters.ClientParameters.TargetHost));
				await clientStream.WriteLineAsync ();
			} catch (Exception ex) {
				ctx.LogMessage ("RECEIVED EXCEPTION WHILE WRITING REQUEST: {0}", ex.Message);
			}

			var line = await clientStream.ReadLineAsync ();
			ctx.LogMessage ("GOT RESPONSE: {0}", line);

			HttpProtocol protocol;
			HttpStatusCode status;
			if (!HttpResponse.ParseResponseHeader (line, out protocol, out status))
				throw new ConnectionException ("Got unexpected output from server: '{0}'", line);

			ctx.LogMessage ("GOT RESPONSE: {0} {1}", protocol, status);

			await Shutdown (ctx, SupportsCleanShutdown, true, cancellationToken);
		}