Search Results

Search found 451 results on 19 pages for 'filestream'.

Page 4/19 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Curl Wrapper Class does not return any data even though it worked previously?

    - by Scott Faisal
    We changed servers and installed all necessary software and just cannot seem to pin point what is going on. A simple CURL request does not return anything. Command Line CURL commands work just fine. We are using a wrapper for CURL utilizing streams. Do PHP streams require any out of the ordinary configuration? We are using the latest Lamp stack. This is the var_dump: object(cURL_Response)#180 (14) { ["cURL:private"]= resource(288) of type (curl) ["data_stream:private"]= object(elTempStream)#178 (1) { ["fp"]= resource(290) of type (stream) } ["request_header:private"]= NULL ["response_header:private"]= object(cURL_Headers)#179 (1) { ["headers:private"]= string(0) "" } ["response_headers:private"]= array(1) { [0]= object(cURL_Headers)#179 (1) { ["headers:private"]= string(0) "" } } ["error:private"]= string(0) "" ["errno:private"]= int(0) ["info:private"]= array(21) { ["url"]= string(21) "http://www.yahoo.com/" ["content_type"]= string(23) "text/html;charset=utf-8" ["http_code"]= int(200) ["header_size"]= int(1195) ["request_size"]= int(1153) ["filetime"]= int(-1) ["ssl_verify_result"]= int(0) ["redirect_count"]= int(1) ["total_time"]= float(0.486924) ["namelookup_time"]= float(0.003692) ["connect_time"]= float(0.005709) ["pretransfer_time"]= float(0.005714) ["size_upload"]= float(0) ["size_download"]= float(28509) ["speed_download"]= float(58549) ["speed_upload"]= float(0) ["download_content_length"]= float(211) ["upload_content_length"]= float(0) ["starttransfer_time"]= float(0.149365) ["redirect_time"]= float(0.312743) ["request_header"]= string(973) "GET / HTTP/1.0 User-Agent: cURL_ClientBase (PHP v/5.2.6-1+lenny4) Host: www.yahoo.com Accept: / Accept-Encoding: gzip, deflate, compress Referer: http://yahoo.com Cookie: B=e5iber15t7u05&b=3&s=ie; fpc_s=d=GGX6WCTIR29HWsjgLxFejKc_YJWxRqm3jYdEd6lu7W5ophpuAHBm6JGtNvhv97anG4VtaIMHQBPg3JAMOZGq59Lz_tRn_TFXgUT8T_at5HdCktVJLycy&v=2; fpt=d=nt1OT7HPe9wVIkHbMkpzQOgbP3.mQ3o1SPX7k5ztrFrWeeSWK5IgQooRY.8KtTeRMiaSEZ0kv3sO1MWtEsAzjVlRCDAZBoxqOs17v6PaZbPRqmDc92ivoMia.CqjufRs4_guOO4AyhRZ7_ml8rzxFrYeexpR2jLN0oPMyEWT0nbEf6Sdf._Bkh0HMfmI7KBnEx5uZBEEmV.wTfGRLG7zSd9sA4itOFv.r6AjP39CnogSn7NTJnqg_kEcKoiCM.lR5w_MqMc8IgWMBgSAZZgGEZpfmvxlQGnUzPwNh2pSpTe2wxFS3v1zPopDgoo2VsO3uzeyA3A_j7Hlk1P8T08DHbfr6ApDMUcr7d0QIt4pGYIxVV45XzfgpT7mgUdMei6VZrD9ozVQF0oqxrs1Ufri.XzPdB3NdQ--&v=1; fpc=d=sRPCfUfBTW96.RGiQn4hSkfi3p7WnPCAqYl5YoHecI7zjg7gH7PolscoPcq1Esm8dR.Rg1.AbQCpo2WBPXn1St96PpcjeCC.pj2.Upb3mKSRQkYPIVP1vQcL9nL7J8s9Z0VIXjiBFgSUcxyzDeUdP4us2YbVO3PbaVIwaIEfFsX3WI7YgiTbkrTGtwnFgoSYq6l8tnw-&v=2" } ["info_flagged:private"]= array(20) { [1048577]= string(21) "http://www.yahoo.com/" [2097154]= int(200) [2097166]= int(-1) [3145731]= float(0.486924) [3145732]= float(0.003692) [3145733]= float(0.005709) [3145734]= float(0.005714) [3145745]= float(0.149365) [3145747]= float(0.312743) [3145735]= float(0) [3145736]= float(28509) [3145737]= float(58549) [3145738]= float(0) [2097163]= int(1195) [2]= string(973) "GET / HTTP/1.0 User-Agent: cURL_ClientBase (PHP v/5.2.6-1+lenny4) Host: www.yahoo.com Accept: / Accept-Encoding: gzip, deflate, compress Referer: http://yahoo.com Cookie: B=e5iber15t7u05&b=3&s=ie; fpc_s=d=GGX6WCTIR29HWsjgLxFejKc_YJWxRqm3jYdEd6lu7W5ophpuAHBm6JGtNvhv97anG4VtaIMHQBPg3JAMOZGq59Lz_tRn_TFXgUT8T_at5HdCktVJLycy&v=2; fpt=d=nt1OT7HPe9wVIkHbMkpzQOgbP3.mQ3o1SPX7k5ztrFrWeeSWK5IgQooRY.8KtTeRMiaSEZ0kv3sO1MWtEsAzjVlRCDAZBoxqOs17v6PaZbPRqmDc92ivoMia.CqjufRs4_guOO4AyhRZ7_ml8rzxFrYeexpR2jLN0oPMyEWT0nbEf6Sdf._Bkh0HMfmI7KBnEx5uZBEEmV.wTfGRLG7zSd9sA4itOFv.r6AjP39CnogSn7NTJnqg_kEcKoiCM.lR5w_MqMc8IgWMBgSAZZgGEZpfmvxlQGnUzPwNh2pSpTe2wxFS3v1zPopDgoo2VsO3uzeyA3A_j7Hlk1P8T08DHbfr6ApDMUcr7d0QIt4pGYIxVV45XzfgpT7mgUdMei6VZrD9ozVQF0oqxrs1Ufri.XzPdB3NdQ--&v=1; fpc=d=sRPCfUfBTW96.RGiQn4hSkfi3p7WnPCAqYl5YoHecI7zjg7gH7PolscoPcq1Esm8dR.Rg1.AbQCpo2WBPXn1St96PpcjeCC.pj2.Upb3mKSRQkYPIVP1vQcL9nL7J8s9Z0VIXjiBFgSUcxyzDeUdP4us2YbVO3PbaVIwaIEfFsX3WI7YgiTbkrTGtwnFgoSYq6l8tnw-&v=2" [2097164]= int(1153) [2097165]= int(0) [3145743]= float(211) [3145744]= float(0) [1048594]= string(23) "text/html;charset=utf-8" } ["request_url:private"]= string(16) "http://yahoo.com" ["response_url:private"]= string(21) "http://www.yahoo.com/" ["status_code:private"]= int(200) ["cookies:private"]= array(0) { } ["request_headers"]= string(973) "GET / HTTP/1.0 User-Agent: cURL_ClientBase (PHP v/5.2.6-1+lenny4) Host: www.yahoo.com Accept: / Accept-Encoding: gzip, deflate, compress Referer: http://yahoo.com Cookie: B=e5iber15t7u05&b=3&s=ie; fpc_s=d=GGX6WCTIR29HWsjgLxFejKc_YJWxRqm3jYdEd6lu7W5ophpuAHBm6JGtNvhv97anG4VtaIMHQBPg3JAMOZGq59Lz_tRn_TFXgUT8T_at5HdCktVJLycy&v=2; fpt=d=nt1OT7HPe9wVIkHbMkpzQOgbP3.mQ3o1SPX7k5ztrFrWeeSWK5IgQooRY.8KtTeRMiaSEZ0kv3sO1MWtEsAzjVlRCDAZBoxqOs17v6PaZbPRqmDc92ivoMia.CqjufRs4_guOO4AyhRZ7_ml8rzxFrYeexpR2jLN0oPMyEWT0nbEf6Sdf._Bkh0HMfmI7KBnEx5uZBEEmV.wTfGRLG7zSd9sA4itOFv.r6AjP39CnogSn7NTJnqg_kEcKoiCM.lR5w_MqMc8IgWMBgSAZZgGEZpfmvxlQGnUzPwNh2pSpTe2wxFS3v1zPopDgoo2VsO3uzeyA3A_j7Hlk1P8T08DHbfr6ApDMUcr7d0QIt4pGYIxVV45XzfgpT7mgUdMei6VZrD9ozVQF0oqxrs1Ufri.XzPdB3NdQ--&v=1; fpc=d=sRPCfUfBTW96.RGiQn4hSkfi3p7WnPCAqYl5YoHecI7zjg7gH7PolscoPcq1Esm8dR.Rg1.AbQCpo2WBPXn1St96PpcjeCC.pj2.Upb3mKSRQkYPIVP1vQcL9nL7J8s9Z0VIXjiBFgSUcxyzDeUdP4us2YbVO3PbaVIwaIEfFsX3WI7YgiTbkrTGtwnFgoSYq6l8tnw-&v=2" }

    Read the article

  • using Object input\ output Streams with files and array list

    - by soad el-hayek
    hi every one .. i'm an it student , and it's time to finish my final project in java , i've faced too many problems , this one i couldn't solve it and i'm really ubset ! :S my code is like this : in Admin class : public ArrayList cos_info = new ArrayList(); public ArrayList cas_info = new ArrayList(); public int cos_count = 0 ; public int cas_count = 0 ; void coustmer_acount() throws FileNotFoundException, IOException{ String add=null; do{ person p = new person() ; cos_info.add(cos_count, p); cos_count ++ ; add =JOptionPane.showInputDialog("Do you want to add more coustmer..\n'y'foryes ..\n 'n'for No .."); } while(add.charAt(0) == 'Y'||add.charAt(0)=='y'); writenew_cos(); // add_acounts(); } void writenew_cos() throws IOException{ ObjectOutputStream aa = new ObjectOutputStream(new FileOutputStream("coustmer.txt")); aa.writeObject(cos_info); JOptionPane.showMessageDialog(null,"Added to file done sucessfuly.."); aa.close(); } in Coustmer class : void read_cos() throws IOException, ClassNotFoundException{ person p1= null ; int array_count = 0; ObjectInputStream d = new ObjectInputStream(new FileInputStream("coustmer.txt")); JOptionPane.showMessageDialog(null,d.available() ); for(int i = 0;d.available() == 0;i++){ a.add(array_count,(ArrayList) d.readObject()); array_count++; JOptionPane.showMessageDialog(null,"Haaaaai :D" ); JOptionPane.showMessageDialog(null,array_count ); } d.close(); JOptionPane.showMessageDialog(null,array_count +"1111" ); for(int i = 0 ; i it just print JOptionPane.showMessageDialog(null,d.available() ); and having excep. here a.add(array_count,(ArrayList) d.readObject()); p.s : person object from my own class and it's Serializabled

    Read the article

  • using Object input\ output Streams with files and array list

    - by soad el-hayek
    hi every one .. i'm an it student , and it's time to finish my final project in java , i've faced too many problems , this one i couldn't solve it and i'm really ubset ! :S my code is like this : in Admin class : public ArrayList cos_info = new ArrayList(); public ArrayList cas_info = new ArrayList(); public int cos_count = 0 ; public int cas_count = 0 ; void coustmer_acount() throws FileNotFoundException, IOException{ String add=null; do{ person p = new person() ; cos_info.add(cos_count, p); cos_count ++ ; add =JOptionPane.showInputDialog("Do you want to add more coustmer..\n'y'foryes ..\n 'n'for No .."); } while(add.charAt(0) == 'Y'||add.charAt(0)=='y'); writenew_cos(); // add_acounts(); } void writenew_cos() throws IOException{ ObjectOutputStream aa = new ObjectOutputStream(new FileOutputStream("coustmer.txt")); aa.writeObject(cos_info); JOptionPane.showMessageDialog(null,"Added to file done sucessfuly.."); aa.close(); } in Coustmer class : void read_cos() throws IOException, ClassNotFoundException{ person p1= null ; int array_count = 0; ObjectInputStream d = new ObjectInputStream(new FileInputStrea ("coustmer.txt")); JOptionPane.showMessageDialog(null,d.available() ); for(int i = 0;d.available() == 0;i++){ a.add(array_count,(ArrayList) d.readObject()); array_count++; JOptionPane.showMessageDialog(null,"Haaaaai :D" ); JOptionPane.showMessageDialog(null,array_count ); } d.close(); JOptionPane.showMessageDialog(null,array_count +"1111" ); for(int i = 0 ; i<a.size()&& found!= true ; i++){ count++ ; p1 =(person)a.get(i); user=p1.user; pass = p1.pass; cas_checkpass(); } } it just print JOptionPane.showMessageDialog(null,d.available() ); and having excep. here a.add(array_count,(ArrayList) d.readObject()); p.s : person object from my own class and it's Serializabled

    Read the article

  • c++ library for endian-aware reading of raw file stream metadata?

    - by Kache4
    I've got raw data streams from image files, like: vector<char> rawData(fileSize); ifstream inFile("image.jpg"); inFile.read(&rawData[0]); I want to parse the headers of different image formats for height and width. Is there a portable library that can can read ints, longs, shorts, etc. from the buffer/stream, converting for endianess as specified? I'd like to be able to do something like: short x = rawData.readLeShort(offset); or long y = rawData.readBeLong(offset) An even better option would be a lightweight & portable image metadata library (without the extra weight of an image manipulation library) that can work on raw image data. I've found that Exif libraries out there don't support png and gif.

    Read the article

  • Attempted to perform an unauthorized operation

    - by Lefteris Gkinis
    Now I use the following code: Public Function SetACL(ByVal filename As String, ByVal account As String, ByVal sender As Object, ByVal e As System.EventArgs) As Boolean Try Dim rule As FileSystemAccessRule = New FileSystemAccessRule(account, FileSystemRights.Write, AccessControlType.Allow) Dim fp As PermissionSet = New PermissionSet(Permissions.PermissionState.Unrestricted) fp.AddPermission(New FileIOPermission(FileIOPermissionAccess.Read, filename)) fp.AddPermission(New FileIOPermission(FileIOPermissionAccess.Write, filename)) fp.AddPermission(New FileIOPermission(FileIOPermissionAccess.PathDiscovery, filename)) fp.Assert() Dim di As DirectoryInfo = New DirectoryInfo(Path.GetDirectoryName(filename)) SetACL = False Dim security As DirectorySecurity = di.GetAccessControl(AccessControlSections.Access) security.ModifyAccessRule(AccessControlModification.Add, rule, SetACL) di.SetAccessControl(security) Return SetACL Catch ex As Exception MessageBox.Show(ex.Message, "Set Security Sub", MessageBoxButtons.OK, MessageBoxIcon.Stop) Finalize() End Try End Function The Error of 'Attempted to perform an unauthorized operation' comes when i'm trying to execute the instraction Dim security As DirectorySecurity = di.GetAccessControl(AccessControlSections.Access) Please if anybody knows why that error comes here to respond

    Read the article

  • What to set the scalar type to contain a byte []. Entity in MVC2

    - by Brad8118
    I'm trying out the EF 4.0 and using the Model first approach. I'd like to store images into the database and I'm not sure of the best type for the scalar in the entity. I currently have it(the image scalar type) setup as a binary. From what I have been reading the best way to store the image in the db is a byte[]. So I'm assuming that binary is the way to go. If there is a better way I'd switch. In my controller I have: //file from client to store in the db HttpPostedFileBase file = Request.Files[inputTagName]; if (file.ContentLength > 0) { keyToAdd.Image = new byte[file.ContentLength]; file.InputStream.Write(keyToAdd.Image, 0, file.ContentLength); } This builds fine but when I run it I get an exception writing the stream to keyToAdd.Image. The exception is something like: Method does not exist. Any ideas? Note that when using a EF 4.0 model first approach I only have int16, int32, double, string, decimal, binary, byte, DateTime, Double, Single, and SByte as available types. Thanks

    Read the article

  • The remote server returned an error: (400) Bad Request - uploading less 2MB file size?

    - by fiberOptics
    The file succeed to upload when it is 2KB or lower in size. The main reason why I use streaming is to be able to upload file up to at least 1 GB. But when I try to upload file with less 1MB size, I get bad request. It is my first time to deal with downloading and uploading process, so I can't easily find the cause of error. Testing part: private void button24_Click(object sender, EventArgs e) { try { OpenFileDialog openfile = new OpenFileDialog(); if (openfile.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string port = "3445"; byte[] fileStream; using (FileStream fs = new FileStream(openfile.FileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { fileStream = new byte[fs.Length]; fs.Read(fileStream, 0, (int)fs.Length); fs.Close(); fs.Dispose(); } string baseAddress = "http://localhost:" + port + "/File/AddStream?fileID=9"; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(baseAddress); request.Method = "POST"; request.ContentType = "text/plain"; //request.ContentType = "application/octet-stream"; Stream serverStream = request.GetRequestStream(); serverStream.Write(fileStream, 0, fileStream.Length); serverStream.Close(); using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { int statusCode = (int)response.StatusCode; StreamReader reader = new StreamReader(response.GetResponseStream()); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } Service: [WebInvoke(UriTemplate = "AddStream?fileID={fileID}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)] public bool AddStream(long fileID, System.IO.Stream fileStream) { ClasslLogic.FileComponent svc = new ClasslLogic.FileComponent(); return svc.AddStream(fileID, fileStream); } Server code for streaming: namespace ClasslLogic { public class StreamObject : IStreamObject { public bool UploadFile(string filename, Stream fileStream) { try { FileStream fileToupload = new FileStream(filename, FileMode.Create); byte[] bytearray = new byte[10000]; int bytesRead, totalBytesRead = 0; do { bytesRead = fileStream.Read(bytearray, 0, bytearray.Length); totalBytesRead += bytesRead; } while (bytesRead > 0); fileToupload.Write(bytearray, 0, bytearray.Length); fileToupload.Close(); fileToupload.Dispose(); } catch (Exception ex) { throw new Exception(ex.Message); } return true; } } } Web config: <system.serviceModel> <bindings> <basicHttpBinding> <binding> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="2097152" maxBytesPerRead="4096" maxNameTableCharCount="2097152" /> <security mode="None" /> </binding> <binding name="ClassLogicBasicTransfer" closeTimeout="00:05:00" openTimeout="00:05:00" receiveTimeout="00:15:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="67108864" maxReceivedMessageSize="67108864" messageEncoding="Mtom" textEncoding="utf-8" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="67108864" maxBytesPerRead="4096" maxNameTableCharCount="67108864" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> <binding name="BaseLogicWSHTTP"> <security mode="None" /> </binding> <binding name="BaseLogicWSHTTPSec" /> </basicHttpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true" /> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" /> </system.serviceModel> I'm not sure if this affects the streaming function, because I'm using WCF4.0 rest template which config is dependent in Global.asax. One more thing is this, whether I run the service and passing a stream or not, the created file always contain this thing. How could I remove the "NUL" data? Thanks in advance. Edit public bool UploadFile(string filename, Stream fileStream) { try { FileStream fileToupload = new FileStream(filename, FileMode.Create); byte[] bytearray = new byte[10000]; int bytesRead, totalBytesRead = 0; do { bytesRead = fileStream.Read(bytearray, totalBytesRead, bytearray.Length - totalBytesRead); totalBytesRead += bytesRead; } while (bytesRead > 0); fileToupload.Write(bytearray, 0, totalBytesRead); fileToupload.Close(); fileToupload.Dispose(); } catch (Exception ex) { throw new Exception(ex.Message); } return true; }

    Read the article

  • Using SQL Server Intergration Services (SSIS) can you read a file from a FileStream column in SQL Se

    - by tbrovold
    I am trying to create a tool that I can upload different types of files "csv", Excel, XML and load those files into a FileStream column in the database as "Source" untouched over the web. Then using SSIS on the server I want to create a package that will process that file to be loaded into other tables to be used by the web application. Is it possible to have SSIS read a file from FileStream column? if so how?

    Read the article

  • send multiple file over TCP with C# using TcpClient

    - by xnoor
    I'm trying to send multiple files over TCP using C# TcpClient, for a single file it works great, but when I have multiple files, it sends only the first one. Here is my code: SENDING FILES try { TcpClient tcpClient = new TcpClient(); NetworkStream networkStream; FileStream fileStream = null; tcpClient.Connect(appUpdateMessage.receiverIpAddress, 12000); networkStream = tcpClient.GetStream(); byte[] byteSend = new byte[tcpClient.ReceiveBufferSize]; string startupPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6); DirectoryInfo directoriesInfo = new DirectoryInfo(startupPath); DirectoryInfo[] directories = directoriesInfo.GetDirectories(); FileInfo[] files = directoriesInfo.GetFiles(); for (int iLoop = 0; iLoop < directories.Length; iLoop++) { FileInfo[] subdirectoryFiles = directories[iLoop].GetFiles(); foreach (FileInfo fi in subdirectoryFiles) { fileStream = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read); BinaryReader binFile = new BinaryReader(fileStream); FileUpdateMessage fileUpdateMessage = new FileUpdateMessage(); fileUpdateMessage.fileName = fi.Name; fileUpdateMessage.fileSize = fi.Length; fileUpdateMessage.targetDirectory = fi.Directory.Name; MessageContainer messageContainer = new MessageContainer(); messageContainer.messageType = MessageType.FileProperties; messageContainer.messageContnet = SerializationManager.XmlFormatterObjectToByteArray(fileUpdateMessage); byte[] messageByte = SerializationManager.XmlFormatterObjectToByteArray(messageContainer); networkStream.Write(messageByte, 0, messageByte.Length); int bytesSize = 0; byte[] downBuffer = new byte[2048]; while ((bytesSize = fileStream.Read(downBuffer, 0, downBuffer.Length)) > 0) { networkStream.Write(downBuffer, 0, bytesSize); } fileStream.Close(); } } tcpClient.Close(); networkStream.Close(); return true; } catch (Exception ex) { //logger.Info(ex.Message); return false; } finally { } RECEIVING FILES try { TcpClient tcpClient = c as TcpClient; NetworkStream networkstream = tcpClient.GetStream(); FileStream fileStream = null; byte[] _data = new byte[1024]; int _bytesRead = 0; _bytesRead = networkstream.Read(_data, 0, _data.Length); MessageContainer messageContainer = new MessageContainer(); messageContainer = SerializationManager.XmlFormatterByteArrayToObject(_data, messageContainer) as MessageContainer; switch (messageContainer.messageType) { case MessageType.FileProperties: FileUpdateMessage fileUpdateMessage = new FileUpdateMessage(); fileUpdateMessage = SerializationManager.XmlFormatterByteArrayToObject(messageContainer.messageContnet, fileUpdateMessage) as FileUpdateMessage; string startupPath = @"d:updatefolder";//System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6); DirectoryInfo mainDirectory = new DirectoryInfo(startupPath); DirectoryInfo targetDirecotry = new DirectoryInfo(startupPath + "\\" + fileUpdateMessage.targetDirectory); if (!targetDirecotry.Exists) { mainDirectory.CreateSubdirectory(fileUpdateMessage.targetDirectory); } fileStream = new FileStream(startupPath + "\\" + fileUpdateMessage.targetDirectory + "\\" + fileUpdateMessage.fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); long filezie = fileUpdateMessage.fileSize; int byteSize = 0; byte[] downBuffer = new byte[2048]; while ((byteSize = networkstream.Read(downBuffer, 0, downBuffer.Length)) > 0) { fileStream.Write(downBuffer, 0, byteSize); if (this.InvokeRequired) { this.Invoke((MethodInvoker)delegate { //progressBar1.Value = Convert.ToInt32((byteSize * 100) / fileUpdateMessage.fileSize); progressBar1.Value = Convert.ToInt32((fileStream.Length * 100) / fileUpdateMessage.fileSize); lblFileName.Text = fileUpdateMessage.fileName; }); } else { //progressBar1.Value = Convert.ToInt32((byteSize * 100) / fileUpdateMessage.fileSize); lblFileName.Text = fileUpdateMessage.fileName; } } fileStream.Close(); networkstream.Close(); break; } } catch (Exception ex) { //logger.Error(ex.Message); } Any idea what I am doing wrong?

    Read the article

  • When downloading a file using FileStream, why does page error message refers to aspx page name, not

    - by StuperUser
    After building a filepath (path, below) in a string (I am aware of Path in System.IO, but am using someone else's code and do not have the opportunity to refactor it to use Path). I am using a FileStream to deliver the file to the user (see below): FileStream myStream = new FileStream(path, FileMode.Open, FileAccess.Read); long fileSize = myStream.Length; byte[] Buffer = new byte[(int)fileSize + 1]; myStream.Read(Buffer, 0, (int)myStream.Length); myStream.Close(); Response.ContentType = "application/csv"; Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.BinaryWrite(Buffer); Response.Flush(); Response.End(); I have seen from: http://stackoverflow.com/questions/736301/asp-net-how-to-stream-file-to-user reasons to avoid use of Response.End() and Response.Close(). I have also seen several articles about different ways to transmit files and have diagnosed and found a solution to the problem (https and http headers) with a colleague. However, the error message that was being displayed was not about access to the file at path, but the aspx file. Edit: Error message is: Internet Explorer cannot download MyPage.aspx from server.domain.tld Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later. (page name and address anonymised) Why is this? Is it due to the contents of the file coming from the HTTP response .Flush() method rather than a file being accessed at its address?

    Read the article

  • DeSerialization doesn't work though i Implement GetObjectData method and Constructor

    - by Punit Singhi
    Hi, I have a static generic dictionary in a class. As static memeber cannot serialized so i have implented ISerializable interface and method GetObjectData to serialize. I have a constructor which will also accept SerializationInfo and StreamingContext to deserliaze the dictionay. Now when i try to serialize and deserialize , it always return 1(thoug i added 2 entries). please find the pseduo code- [Serializable] public class MyClass : ISerializable { internal static Dictionary<long, string> dict = new Dictionary<long,string>(); public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("static.dic", MyClass1.dict, typeof(Dictionary<long, string>)); } public MyClass(SerializationInfo info, StreamingContext context) { MyClass.dict= (Dictionary<long, string>)info.GetValue("static.dic", typeof(Dictionary<long, string>)); } public void Add() { dict.Add(21, "11"); } public MyClass() { dict.Add(21, "11"); } } public class MyClass { MyClass myClass = new MyClass(); public static void Main() { myClass.Add(); FileStream fileStream = new FileStream("test.binary", FileMode.Create); IFormatter bf = new BinaryFormatter(); bf.Serialize(fileStream, myClass); fileStream.Dispose(); fileStream.Close(); fileStream = new FileStream("test.binary", FileMode.Open); bf = new BinaryFormatter(); myClass = (MyClass1)bf.Deserialize(fileStream); } }

    Read the article

  • Could I return a FileStream as a generic interface to a file?

    - by Eric
    I'm writing a class interface that needs to return references to binary files. Typically I would provide a reference to a file as a file path. However, I'm considering storing some of the files (such as a small thumbnail) in a database directly rather then on a file system. In this case I don't want to add the extra step of reading the thumbnail out of the database onto the disc and then returning a path to the file for my program to read. I'd want to stream the image directly out of the database into my program and avoid writing anything to the disc unless the user explicit wants to save something. Would having my interface return a FileStreamor even a Imagemake sense? Then it would be up to the implementing class to determine if the source of the FileStream or Image is a file on a disc or binary data in a database. public interface MyInterface { string Thumbnail {get;} string Attachment {get;} } vs public interface MyInterface { Image Thumbnail {get;} FileStream Attachment {get;} }

    Read the article

  • Is it possible to pass a structure of delegates from managed to native?

    - by Veiva
    I am writing a wrapper for the game programming library "Allegro" and its less stable 4.9 branch. Now, I have done good insofar, except for when it comes to wrapping a structure of function pointers. Basically, I can't change the original code, despite having access to it, because that would require me to fork it in some manner. I need to know how I can somehow pass a structure of delegates from managed to native without causing an AccessViolationException that has occurred so far. Now, for the code. Here is the Allegro definition of the structure: typedef struct ALLEGRO_FILE_INTERFACE { AL_METHOD(ALLEGRO_FILE*, fi_fopen, (const char *path, const char *mode)); AL_METHOD(void, fi_fclose, (ALLEGRO_FILE *handle)); AL_METHOD(size_t, fi_fread, (ALLEGRO_FILE *f, void *ptr, size_t size)); AL_METHOD(size_t, fi_fwrite, (ALLEGRO_FILE *f, const void *ptr, size_t size)); AL_METHOD(bool, fi_fflush, (ALLEGRO_FILE *f)); AL_METHOD(int64_t, fi_ftell, (ALLEGRO_FILE *f)); AL_METHOD(bool, fi_fseek, (ALLEGRO_FILE *f, int64_t offset, int whence)); AL_METHOD(bool, fi_feof, (ALLEGRO_FILE *f)); AL_METHOD(bool, fi_ferror, (ALLEGRO_FILE *f)); AL_METHOD(int, fi_fungetc, (ALLEGRO_FILE *f, int c)); AL_METHOD(off_t, fi_fsize, (ALLEGRO_FILE *f)); } ALLEGRO_FILE_INTERFACE; My simple attempt at wrapping it: public delegate IntPtr AllegroInternalOpenFileDelegate(string path, string mode); public delegate void AllegroInternalCloseFileDelegate(IntPtr file); public delegate int AllegroInternalReadFileDelegate(IntPtr file, IntPtr data, int size); public delegate int AllegroInternalWriteFileDelegate(IntPtr file, IntPtr data, int size); public delegate bool AllegroInternalFlushFileDelegate(IntPtr file); public delegate long AllegroInternalTellFileDelegate(IntPtr file); public delegate bool AllegroInternalSeekFileDelegate(IntPtr file, long offset, int where); public delegate bool AllegroInternalIsEndOfFileDelegate(IntPtr file); public delegate bool AllegroInternalIsErrorFileDelegate(IntPtr file); public delegate int AllegroInternalUngetCharFileDelegate(IntPtr file, int c); public delegate long AllegroInternalFileSizeDelegate(IntPtr file); [StructLayout(LayoutKind.Sequential, Pack = 0)] public struct AllegroInternalFileInterface { [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalOpenFileDelegate fi_fopen; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalCloseFileDelegate fi_fclose; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalReadFileDelegate fi_fread; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalWriteFileDelegate fi_fwrite; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalFlushFileDelegate fi_fflush; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalTellFileDelegate fi_ftell; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalSeekFileDelegate fi_fseek; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalIsEndOfFileDelegate fi_feof; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalIsErrorFileDelegate fi_ferror; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalUngetCharFileDelegate fi_fungetc; [MarshalAs(UnmanagedType.FunctionPtr)] public AllegroInternalFileSizeDelegate fi_fsize; } I have a simple auxiliary wrapper that turns an ALLEGRO_FILE_INTERFACE into an ALLEGRO_FILE, like so: #define ALLEGRO_NO_MAGIC_MAIN #include <allegro5/allegro5.h> #include <stdlib.h> #include <string.h> #include <assert.h> __declspec(dllexport) ALLEGRO_FILE * al_aux_create_file(ALLEGRO_FILE_INTERFACE * fi) { ALLEGRO_FILE * file; assert(fi && "`fi' null"); file = (ALLEGRO_FILE *)malloc(sizeof(ALLEGRO_FILE)); if (!file) return NULL; file->vtable = (ALLEGRO_FILE_INTERFACE *)malloc(sizeof(ALLEGRO_FILE_INTERFACE)); if (!(file->vtable)) { free(file); return NULL; } memcpy(file->vtable, fi, sizeof(ALLEGRO_FILE_INTERFACE)); return file; } __declspec(dllexport) void al_aux_destroy_file(ALLEGRO_FILE * f) { assert(f && "`f' null"); assert(f->vtable && "`f->vtable' null"); free(f->vtable); free(f); } Lastly, I have a class that accepts a Stream and provides the proper methods to interact with the stream. Just to make sure, here it is: /// <summary> /// A semi-opaque data type that allows one to load fonts, etc from a stream. /// </summary> public class AllegroFile : AllegroResource, IDisposable { AllegroInternalFileInterface fileInterface; Stream fileStream; /// <summary> /// Gets the file interface. /// </summary> internal AllegroInternalFileInterface FileInterface { get { return fileInterface; } } /// <summary> /// Constructs an Allegro file from the stream provided. /// </summary> /// <param name="stream">The stream to use.</param> public AllegroFile(Stream stream) { fileStream = stream; fileInterface = new AllegroInternalFileInterface(); fileInterface.fi_fopen = Open; fileInterface.fi_fclose = Close; fileInterface.fi_fread = Read; fileInterface.fi_fwrite = Write; fileInterface.fi_fflush = Flush; fileInterface.fi_ftell = GetPosition; fileInterface.fi_fseek = Seek; fileInterface.fi_feof = GetIsEndOfFile; fileInterface.fi_ferror = GetIsError; fileInterface.fi_fungetc = UngetCharacter; fileInterface.fi_fsize = GetLength; Resource = AllegroFunctions.al_aux_create_file(ref fileInterface); if (!IsValid) throw new AllegroException("Unable to create file"); } /// <summary> /// Disposes of all resources. /// </summary> ~AllegroFile() { Dispose(); } /// <summary> /// Disposes of all resources used. /// </summary> public void Dispose() { if (IsValid) { Resource = IntPtr.Zero; // Should call AllegroFunctions.al_aux_destroy_file fileStream.Dispose(); } } IntPtr Open(string path, string mode) { return IntPtr.Zero; } void Close(IntPtr file) { fileStream.Close(); } int Read(IntPtr file, IntPtr data, int size) { byte[] d = new byte[size]; int read = fileStream.Read(d, 0, size); Marshal.Copy(d, 0, data, size); return read; } int Write(IntPtr file, IntPtr data, int size) { byte[] d = new byte[size]; Marshal.Copy(data, d, 0, size); fileStream.Write(d, 0, size); return size; } bool Flush(IntPtr file) { fileStream.Flush(); return true; } long GetPosition(IntPtr file) { return fileStream.Position; } bool Seek(IntPtr file, long offset, int whence) { SeekOrigin origin = SeekOrigin.Begin; if (whence == 1) origin = SeekOrigin.Current; else if (whence == 2) origin = SeekOrigin.End; fileStream.Seek(offset, origin); return true; } bool GetIsEndOfFile(IntPtr file) { return fileStream.Position == fileStream.Length; } bool GetIsError(IntPtr file) { return false; } int UngetCharacter(IntPtr file, int character) { return -1; } long GetLength(IntPtr file) { return fileStream.Length; } } Now, when I do something like this: AllegroFile file = new AllegroFile(new FileStream("Test.bmp", FileMode.Create, FileAccess.ReadWrite)); bitmap.SaveToFile(file, ".bmp"); ...I get an AccessViolationException. I think I understand why (the garbage collector can relocate structs and classes whenever), but I'd think that the method stub that is created by the framework would take this into consideration and route the calls to the valid classes. However, it seems obviously so that I'm wrong. So basically, is there any way I can successfully wrap that structure? (And I'm sorry for all the code! Hope it's not too much...)

    Read the article

  • Design guideline for saving big byte stream in c# [migrated]

    - by Praveen
    I have an application where I am receiving big byte array very fast around per 50 miliseconds. The byte array contains some information like file name etc. The data (byte array ) may come from several sources. Each time I receive the data, I have to find the file name and save the data to that file name. I need some guide lines to how should I design it so that it works efficient. Following is my code... public class DataSaver { private static Dictionary<string, FileStream> _dictFileStream; public static void SaveData(byte[] byteArray) { string fileName = GetFileNameFromArray(byteArray); FileStream fs = GetFileStream(fileName); fs.Write(byteArray, 0, byteArray.Length); } private static FileStream GetFileStream(string fileName) { FileStream fs; bool hasStream = _dictFileStream.TryGetValue(fileName, out fs); if (!hasStream) { fs = new FileStream(fileName, FileMode.Append); _dictFileStream.Add(fileName, fs); } return fs; } public static void CloseSaver() { foreach (var key in _dictFileStream.Keys) { _dictFileStream[key].Close(); } } } How can I improve this code ? I need to create a thread maybe to do the saving.

    Read the article

  • Splitting TIFF Files on different formats using .NET

    - by Jojo
    HI All, I have below code to extract a single page from a multi-paged TIFF file. The problem is, the input file is in CCITT Group 4 compression however the output compression is LZW. Can .NET outputs TIFF files other than this compression? FileStream fileStream = File.Open(outputFileName, FileMode.Create, FileAccess.ReadWrite); sourceImage.SelectActiveFrame(firstFrameDimension, pageNumbers[i]); sourceImage.Save(fileStream, ImageFormat.Tiff); fileStream.Close();

    Read the article

  • How do I read a binary file in C#?

    - by tomcamara
    I have a file that exists within a text and a binary image, I need to read from 0 to 30 position the text in question, and the position on 31 would be the image in binary format. What are the steps that I have to follow to proceed with that problem? Currently, I am trying to read it using FileStream, and then I move the FileStream var to one BinaryReader as shown below: FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read) BinaryReader br = new BinaryReader(fs) From there forward, I'm lost.

    Read the article

  • as3crypto PEM.readRSAPublicKey returns null

    - by www.jefferyfernandez.id.au
    I am trying to implement a bit of encryption in my Air application while communication with a PHP backend server. For this purpose I am using as3crypto library and I can't read the public key to make the encryption possible. Here is my action script code: var rsa:RSAKey = PEM.readRSAPublicKey(this.readApplicationFileContents('server.crt')); if ( rsa ) { var encodeSource:ByteArray = Hex.toArray(Hex.fromString("Hello World")); var encodeDestination:ByteArray = new ByteArray; var encodeDestination2:ByteArray = new ByteArray; rsa.encrypt(encodeSource, encodeDestination, encodeSource.length) rsa.decrypt(encodeDestination, encodeDestination2, encodeDestination.length); trace(encodeDestination2.toString()); } private function readApplicationFileContents(filePath:String):String { var fileObject:File = File.applicationDirectory.resolvePath(filePath); var fileStream:FileStream = new FileStream(); fileStream.open(fileObject, FileMode.READ); var fileContents:String = fileStream.readUTFBytes(fileStream.bytesAvailable); return(fileContents); } readApplicationFileContents function returns the proper certificate contents as a string. But rsa variable always returns null. It would have been easier if I was able to compile the as3crypto library so I can debug through the source, but I can't get the library to compile and can't find any instructions to do the same. Anyone have a clue what's wrong? PS. Sorry first time poster and I can't seem to get the syntax highlighting right. Must be Chrome is not working well with the editor.

    Read the article

  • Should you declare methods using overloads or optional parameters in C# 4.0?

    - by Greg Beech
    I was watching Anders' talk about C# 4.0 and sneak preview of C# 5.0, and it got me thinking about when optional parameters are available in C# what is going to be the recommended way to declare methods that do not need all parameters specified? For example something like the FileStream class has about fifteen different constructors which can be divided into logical 'families' e.g. the ones below from a string, the ones from an IntPtr and the ones from a SafeFileHandle. FileStream(string,FileMode); FileStream(string,FileMode,FileAccess); FileStream(string,FileMode,FileAccess,FileShare); FileStream(string,FileMode,FileAccess,FileShare,int); FileStream(string,FileMode,FileAccess,FileShare,int,bool); It seems to me that this type of pattern could be simplified by having three constructors instead, and using optional parameters for the ones that can be defaulted, which would make the different families of constructors more distinct [note: I know this change will not be made in the BCL, I'm talking hypothetically for this type of situation]. What do you think? From C# 4.0 will it make more sense to make closely related groups of constructors and methods a single method with optional parameters, or is there a good reason to stick with the traditional many-overload mechanism?

    Read the article

  • Method returns an IDisposable - Should I dispose of the result, even if it's not assigned to anythin

    - by mjd79
    This seems like a fairly straightforward question, but I couldn't find this particular use-case after some searching around. Suppose I have a simple method that, say, determines if a file is opened by some process. I can do this (not 100% correctly, but fairly well) with this: public bool IsOpen(string fileName) { try { File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None); } catch { // if an exception is thrown, the file must be opened by some other process return true; } } (obviously this isn't the best or even correct way to determine this - File.Open throws a number of different exceptions, all with different meanings, but it works for this example) Now the File.Open call returns a FileStream, and FileStream implements IDisposable. Normally we'd want to wrap the usage of any FileStream instantiations in a using block to make sure they're disposed of properly. But what happens in the case where we don't actually assign the return value to anything? Is it still necessary to dispose of the FileStream, like so: try { using (File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None)); { /* nop */ } } catch { return true; } Should I create a FileStream instance and dispose of that? try { using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None)); } ... Or are these totally unnecessary? Can we simply call File.Open and not assign it to anything (first code example), and let the GC dispose of it right away?

    Read the article

  • Saving image to database as varbinary, arraylength (part 2)

    - by Thomas Schoof
    This is a followup to my previous question, which got solved (thank you for that) but now I am stuck at another error. I'm trying to save an image in my database (called 'Afbeelding'), for that I made a table which excists of: id: int souce: varbinary(max) I then created a wcf service to save an 'Afbeelding' to the database. private static DataClassesDataContext dc = new DataClassesDataContext(); [OperationContract] public void setAfbeelding(Afbeelding a) { //Afbeelding a = new Afbeelding(); //a.id = 1; //a.source = new Binary(bytes); dc.Afbeeldings.InsertOnSubmit(a); dc.SubmitChanges(); } I then put a reference to the service in my project and when I press the button I try to save it to the datbase. private void btnUpload_Click(object sender, RoutedEventArgs e) { Afbeelding a = new Afbeelding(); OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "JPEG files|*.jpg"; if (openFileDialog.ShowDialog() == true) { //string imagePath = openFileDialog.File.Name; //FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read); //byte[] buffer = new byte[fileStream.Length]; //fileStream.Read(buffer, 0, (int)fileStream.Length); //fileStream.Close(); Stream stream = (Stream)openFileDialog.File.OpenRead(); Byte[] bytes = new Byte[stream.Length]; stream.Read(bytes, 0, (int)stream.Length); string fileName = openFileDialog.File.Name; a.id = 1; a.source = new Binary { Bytes = bytes }; } EditAfbeeldingServiceClient client = new EditAfbeeldingServiceClient(); client.setAfbeeldingCompleted +=new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_setAfbeeldingCompleted); client.setAfbeeldingAsync(a); } void client_setAfbeeldingCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { if (e.Error != null) txtEmail.Text = e.Error.ToString(); else MessageBox.Show("WIN"); } However, when I do this, I get the following error: System.ServiceModel.FaultException: The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter :a. The InnerException message was 'There was an error deserializing the object of type OndernemersAward.Web.Afbeelding. The maximum array length quota (16384) has been exceeded while reading XML data. This quota may be increased by changing the MaxArrayLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader.'. Please see InnerException for more details. at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc) at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result) at System.ServiceModel.ClientBase`1.ChannelBase`1.EndInvoke(String methodName, Object[] args, IAsyncResult result) atOndernemersAward.EditAfbeeldingServiceReference.EditAfbeeldingServiceClient.EditAfbeeldingServiceClientChannel.EndsetAfbeelding(IAsyncResult result) at OndernemersAward.EditAfbeeldingServiceReference.EditAfbeeldingServiceClient.OndernemersAward.EditAfbeeldingServiceReference.EditAfbeeldingService.EndsetAfbeelding(IAsyncResult result) at OndernemersAward.EditAfbeeldingServiceReference.EditAfbeeldingServiceClient.OnEndsetAfbeelding(IAsyncResult result) at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result) I'm not sure what's causing this but I think it has something to do with the way I write the image to the database? (The array length is too big big, I don't really know how to change it) Thank you for your help, Thomas

    Read the article

  • Getting NLog Running in Partial Trust

    - by grant.barrington
    To get things working you will need to: Strong name sign the assembly Allow Partially Trusted Callers In the AssemblyInfo.cs file you will need to add the assembly attribute for “AllowPartiallyTrustedCallers” You should now be able to get NLog working as part of a partial trust installation, except that the File target won’t work. Other targets will still work (database for example)   Changing BaseFileAppender.cs to get file logging to work In the directory \Internal\FileAppenders there is a file called “BaseFileAppender.cs”. Make a change to the function call “TryCreateFileStream()”. The error occurs here: Change the function call to be: private FileStream TryCreateFileStream(bool allowConcurrentWrite) { FileShare fileShare = FileShare.Read; if (allowConcurrentWrite) fileShare = FileShare.ReadWrite; #if DOTNET_2_0 if (_createParameters.EnableFileDelete && PlatformDetector.GetCurrentRuntimeOS() != RuntimeOS.Windows) { fileShare |= FileShare.Delete; } #endif #if !NETCF try { if (PlatformDetector.IsCurrentOSCompatibleWith(RuntimeOS.WindowsNT) || PlatformDetector.IsCurrentOSCompatibleWith(RuntimeOS.Windows)) { return WindowsCreateFile(FileName, allowConcurrentWrite); } } catch (System.Security.SecurityException secExc) { InternalLogger.Error("Security Exception Caught in WindowsCreateFile. {0}", secExc.Message); } #endif return new FileStream(FileName, FileMode.Append, FileAccess.Write, fileShare, _createParameters.BufferSize); }   Basically we wrap the call in a try..catch. If we catch a SecurityException when trying to create the FileStream using WindowsCreateFile(), we just swallow the exception and use the native System.Io.FileStream instead.

    Read the article

  • Calling a .NET C# class from XSLT

    - by HanSolo
    If you've ever worked with XSLT, you'd know that it's pretty limited when it comes to its programming capabilities. Try writing a for loop in XSLT and you'd know what I mean. XSLT is not designed to be a programming language so you should never put too much programming logic in your XSLT. That code can be a pain to write and maintain and so it should be avoided at all costs. Keep your xslt simple and put any complex logic that your xslt transformation requires in a class. Here is how you can create a helper class and call that from your xslt. For example, this is my helper class:  public class XsltHelper     {         public string GetStringHash(string originalString)         {             return originalString.GetHashCode().ToString();         }     }   And this is my xslt file(notice the namespace declaration that references the helper class): <?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:ext="http://MyNamespace">     <xsl:output method="text" indent="yes" omit-xml-declaration="yes"/>     <xsl:template  match="/">The hash code of "<xsl:value-of select="stringList/string1" />" is "<xsl:value-of select="ext:GetStringHash(stringList/string1)" />".     </xsl:template> </xsl:stylesheet>   Here is how you can include the helper class as part of the transformation: string xml = "<stringList><string1>test</string1></stringList>";             XmlDocument xmlDocument = new XmlDocument();             xmlDocument.LoadXml(xml);               XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();             xslCompiledTransform.Load("XSLTFile1.xslt");               XsltArgumentList xsltArgs = new XsltArgumentList();                        xsltArgs.AddExtensionObject("http://MyNamespace", Activator.CreateInstance(typeof(XsltHelper)));               using (FileStream fileStream = new FileStream("TransformResults.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))             {                 // transform the xml and output to the output file ...                 xslCompiledTransform.Transform(xmlDocument, xsltArgs, fileStream);                            }

    Read the article

  • AS3 Working With Arbitrarily Large Files

    - by Kekoa
    I am trying to read a very large file in AS3 and am having problems with the runtime just crashing on me. I'm currently using a FileStream to open the file asynchronously. This does not work(crashes without an Exception) for files bigger than about 300MB. _fileStream = new FileStream(); _fileStream.addEventListener(IOErrorEvent.IO_ERROR, loadError); _fileStream.addEventListener(Event.COMPLETE, loadComplete); _fileStream.openAsync(myFile, FileMode.READ); In looking at the documentation, it sounds like the FileStream class still tries to read in the entire file to memory(which is bad for large files). Is there a more suitable class to use for reading large files? I really would like something like a buffered FileStream class that only loads the bytes from the files that are going to be read next. I'm expecting that I may need to write a class that does this for me, but then I would need to read only a piece of a file at a time. I'm assuming that I can do this by setting the position and readAhead properties of the FileStream to read a chunk out of a file at a time. I would love to save some time if there is a class like this that already exists. Is there a good way to process large files in AS3, without loading entire contents into memory?

    Read the article

  • VB.NET Debug Error

    - by Daniel
    I get this error "Illegal characters in path" for this code: Dim strm As System.IO.FileStream strm = New System.IO.FileStream(filepath, IO.FileMode.Open, IO.FileAccess.Read)

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >