
MTSkull
Avatar/Signature-
Posts
153 -
Joined
-
Last visited
Content Type
Profiles
Forums
Blogs
Events
Articles
Resources
Downloads
Gallery
Everything posted by MTSkull
-
Exact coding is difficult without knowing precisely what you are doing. This sounds like it might be an advanced project. Some hints. 1. Look up how to use Process.Start() this will allow you to run/monitor an external program. 2. When the user requests to start the new process, you are going to want to monitor/check the other running Processes, and see if it is running or not. By checking the Process.HasExited property you can see if a process has stopped. 3. I think there might be easier ways to do what you want. 4. Google is your friend 5. My post here shows one way to do something similar. Also you should have a try at doing this yourself. If you have problems come back and post specifics and the Pros here will do their best to solve it. Good Luck MTS
-
Fixed... I could not find anyone who had a similar problem, despite hours running various Google searches. I thought I might have a corrupt install or something, so I created a project to test the PreviousPage property and Source.Transfer() function, while stripping away everything else that was irrelevant to the problem. Everything worked as expected. Then I looked closer at the error message and noticed that "ASP.fieldservice_generatemr_aspx" seemed to point to the wrong location. It should have been ASP.fieldservice_SUBFOLDER_generatemr_aspx. Which lead me to suspect I had created the error, which is usually the problem. About a month ago I had moved the source page file into a sub folder in the project after I had created the page. When you create the page the project knows where it is. Then when you move it (drag and drop to new folder) something does not get updated with the new location. When you try to use <%@ PreviousPageType VirtualPath="SourcePage.aspx" %> the program freaks out because it cannot find the source form and cannot cast the page to the appropriate object. I could not find where the update to reflect the move needed to occur (didn't really look:rolleyes:) so to fix I renamed the old page and recreated a new page with the old pages original name. Then copied and pasted the code from the old to the new and presto, everything started working as expected. I should start a blog "How not to code ASPX pages." MTS
-
I realize this is old but, you might try posting some code. Some times that can let the Pros here see what is happening. Also if you fix it yourself while waiting for an answer, please come back and post your fix so others with similar problems will benefit from your experience. Have you tried using the code behind for validation, or is everything handled in Javascript. Thanks MTS
-
I have a web form that takes in user input. Then I transfer to a Processing page that tells the user to wait while some stuff is happening, and plays a simple flash animation. Source page (GenerateMR) protected void cmdGenerateMR_Click(object sender, EventArgs e) { Server.Transfer("MRProcessing.aspx",true); } Then I try to set an object on the destination page so I can read back the values entered on the source page. Destination Page (MRProcessing) private GenerateMR frmSource; protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; //Following throws InvalidCastException //Unable to cast object of type 'ASP.fieldservice_generatemr_aspx' to type 'FieldReturns.GenerateMR'. //frmSource = (GenerateMR)Context.Handler; //also generates above error.. GenerateMR frmSource = (GenerateMR)PreviousPage; } Basically I want to switch to a "Processing files, Please Wait" Page while I am doing stuff on the server. Is this method a good fit, if I can get it working or should I be doing something else. Thanks MTS
-
Just noticed that I failed to respond to this sorry. The "less then successful" was user error. I verified that the server uses local time. I just mis-adjusted the test PC's time and ran the function.
-
Figured it out. You cannot access the redirected output or error data while the process is running. once the process has stopped then you can look at the data. I think because I am actively sending data and have to explicitly send an "exit" command, the output is unavailable. The following mods to previously posted code work. public void UploadFileViaPSFTP(string ServerName, string UserName, string Password, string FileName) { // loop variables int loopThrottle = 1000; // controls how fast the loop sends commands to the process // : 1000 works // : 500 works // : 250 works, will use this for now // : 100 is too fast, transfer does not happen string[] commands = new string[]{"open " + ServerName, UserName, Password, "put \"" + FileName + "\"",// file name and path needs double quotes "ls", "exit"}; // Setup psftp process // psftp.exe download from "http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html" // select putty.zip for multiple utilities Process psftp = new Process(); psftp.StartInfo.UseShellExecute = false; // has to be false to allow stream redirection psftp.StartInfo.FileName = Server.MapPath("SSH_Tools") + "\\psftp.exe"; // allows uploading a file to a remote server psftp.StartInfo.CreateNoWindow = true; // allow console input/out stream redirection psftp.StartInfo.RedirectStandardInput = true; psftp.StartInfo.RedirectStandardOutput = true; psftp.StartInfo.RedirectStandardError = true; // Start Process, psftp.Start(); System.Threading.Thread.Sleep(loopThrottle); StreamWriter psftpIn = psftp.StandardInput; // redirect input to console //Loop to send console commands for (int x = 0; x < commands.Length; x++) { psftpIn.WriteLine(commands[x]); System.Threading.Thread.Sleep(loopThrottle); } // give things a chance to settle System.Threading.Thread.Sleep(loopThrottle * 5); psftp.WaitForExit(); LogToTextFile("UploadFileViaPSFTP", commands, psftp.StandardOutput, psftp.StandardError); // clean up... psftpIn.Close(); psftp.Close(); } private void LogToTextFile(string processName, string[] commands, StreamReader Output, StreamReader Error) { string filename = Server.MapPath("SSH_Tools") + "\\ErrorLog.txt"; string dtStamp = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": "; StreamWriter ftpLog = new StreamWriter(filename, true); ftpLog.WriteLine(); ftpLog.WriteLine("<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>"); ftpLog.WriteLine(); ftpLog.WriteLine(dtStamp + processName); // write commands for (int x = 0; x < commands.Length; x++) ftpLog.WriteLine(string.Format("{0}COMMAND: [{1}]: {2}",dtStamp, x, commands[x])); // write output data if (Output.EndOfStream == true) ftpLog.WriteLine(dtStamp + "OUTPUT : EOF, no output available."); else { while (Output.EndOfStream != true) ftpLog.WriteLine(dtStamp + "OUTPUT : " + Output.ReadLine()); } //write error data if (Error.EndOfStream == true) ftpLog.WriteLine(dtStamp + "ERROR : EOF, no error available"); else { while (Error.EndOfStream != true) ftpLog.WriteLine(dtStamp + "ERROR : " + Error.ReadToEnd()); } ftpLog.Close(); }
-
I am launching a process that uploads a file to a remote server. Then I will launch a second process that will run a script on the remote server to process the file. All of which works except... I would like to read the console outputs so i can tell if what I am doing is working. When I set up the process to redirect to a standard output stream, if I call any of the Read(), ReadBlock(), etc, commands, the program hangs. If I try to run the reads in an event, the event code never fires. If i call the Peek command I can see the First char that would be expected if I was running the console manually. Is there something I can do to get the read to work? Thanks MTS EDIT: This is in code behind for a aspx page, Should this be posted else where? Some code to peruse... public void UploadFileViaPSFTP(string ServerName, string UserName, string Password, string FileName) { // open log file, overwrite existing StreamWriter ftpLog = new StreamWriter("C:\\psftpLog.txt", false); // create a new log file ftpLog.WriteLine("Start Copy Process:" + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString()); ftpLog.Close(); // loop variables int loopThrottle = 250; // controls how fast the loop sends commands to the process // : 1000 works // : 500 works // : 250 works, will use this for now // : 100 is too fast, transfer does not happen string[] commands = new string[]{"open " + ServerName, UserName, Password, "put \"" + FileName + "\""}; // file name and path needs double quotes // Setup psftp process // psftp.exe download from "http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html" // select putty.zip for multiple utilities Process psftp = new Process(); psftp.StartInfo.UseShellExecute = false; // has to be false to allow stream redirection psftp.StartInfo.FileName = "C:\\ssh_tools\\psftp.exe"; // allows uploading a file to a remote server psftp.StartInfo.CreateNoWindow = true; // event handler for psftp data output // Does not work, will troubleshoot as needed //psftp.OutputDataReceived += new DataReceivedEventHandler(RedirectConsoleToTextFile); // allow console input/out stream redirection psftp.StartInfo.RedirectStandardInput = true; psftp.StartInfo.RedirectStandardOutput = true; // Start Process, psftp.Start(); System.Threading.Thread.Sleep(loopThrottle); StreamWriter psftpIn = psftp.StandardInput; // redirect input to console // Hangs, never returns data //string data = psftp.StandardOutput.ReadToEnd(); //Will see the first char in the console output! Grrr, how do I read this? int data = psftp.StandardOutput.Peek(); //Loop to send console commands for (int x = 0; x < commands.Length; x++) { psftpIn.WriteLine(commands[x]); System.Threading.Thread.Sleep(loopThrottle); } // give things a chance to settle System.Threading.Thread.Sleep(loopThrottle * 5); // clean up... psftpIn.Close(); psftp.Close(); } private static void RedirectConsoleToTextFile(object sendingProcess, DataReceivedEventArgs outLine) { bool append = true; // redirect console output to text file // NOTE: never fires if (String.IsNullOrEmpty(outLine.Data) != true) { if (File.Exists("C:\\psftpLog.txt") != true) append = false; // create the file if it does not exist StreamWriter ftpLog = new StreamWriter("C:\\psftpLog.txt", append); ftpLog.Write(outLine.ToString()); ftpLog.Close(); } }
-
I have an asp application with c# code behind which will be used to collect user entered data from all over the place. I am going to stamp the data with... string.Format("{0: yyyy-MM-dd H:mm} MST", DateTime.Now); This is going to happen in the code behind at the server. So the question is, will the stamp be the local time at the server, or the local time for the end user? I tried to set up an experiment but it was less the successful. Thanks MTS
-
I think I am having a similar problem. I have an asp page that has c# elements and some javascript elements. If the code is run from the local machine in debug the code works fine in IE, Firefox and Chrome. When I publish the website to the IIS Server it still works in IE and chrome, but fails to work in Firefox. When posting to this forum adding code helps. Here is a sample of my code. I am creating a menu bar at the top with some dynamic elements. I copied the code from another website. It links to external Webpages and internal anchors. I would try searching for why Javascript does not work for aspx in firefox. If I find anything I will post results here. Also Google is a programmers best friend. <script type="text/javascript"> //SuckerTree Horizontal Menu (Sept 14th, 06) //By Dynamic Drive: http://www.dynamicdrive.com/style/ var menuids=["treemenu1"] //Enter id(s) of SuckerTree UL menus, separated by commas function buildsubmenus_horizontal() { for (var i = 0; i < menuids.length; i++) { var ultags=document.getElementById(menuids[i]).getElementsByTagName("ul") for (var t = 0; t < ultags.length; t++) { if (ultags[t].parentNode.parentNode.id == menuids[i]) { //if this is a first level submenu ultags[t].style.top=ultags[t].parentNode.offsetHeight+"px" //dynamically position first level submenus to be height of main menu item ultags[t].parentNode.getElementsByTagName("a")[0].className="mainfoldericon" } else { //else if this is a sub level menu (ul) ultags[t].style.left=ultags[t-1].getElementsByTagName("a")[0].offsetWidth+"px" //position menu to the right of menu item that activated it ultags[t].parentNode.getElementsByTagName("a")[0].className="subfoldericon" } ultags[t].parentNode.onmouseover = function() { this.getElementsByTagName("ul")[0].style.visibility="visible" } ultags[t].parentNode.onmouseout = function() { this.getElementsByTagName("ul")[0].style.visibility="hidden" } } } } if (window.addEventListener) window.addEventListener("load", buildsubmenus_horizontal, false) else if (window.attachEvent) window.attachEvent("onload", buildsubmenus_horizontal) </script> <div class="suckertreemenu"> <ul id="treemenu1"> <li><a href="TyphonHome.aspx">Home</a></li> <li><a href="Search.aspx">Search</a></li> <li><a href="#Custom">Custom Data</a></li> <li><a href="#Laptop">Laptop</a></li> <li><a href="#System">System</a></li> <li><a href="#WiFi">WiFi</a></li> </ul> <br style="clear: left;" /> </div> Here is the CSS stuff /****** Sucker Tree CSS Data ******/ /*Credits: Dynamic Drive CSS Library */ /*URL: http://www.dynamicdrive.com/style/ */ .suckertreemenu ul{ margin: 0; padding: 0; list-style-type: none; } /*Top level list items*/ .suckertreemenu ul li{ position: relative; display: inline; float: left; background-color: #F3F3F3; /*overall menu background color*/ } /*Top level menu link items style*/ .suckertreemenu ul li a{ display: block; width: 90px; /*Width of top level menu link items*/ padding: 1px 8px; border: 1px solid black; border-left-width: 0; text-decoration: none; color: navy; } /*1st sub level menu*/ .suckertreemenu ul li ul{ left: 0; position: absolute; top: 1em; /* no need to change, as true value set by script */ display: block; visibility: hidden; } /*Sub level menu list items (undo style from Top level List Items)*/ .suckertreemenu ul li ul li{ display: list-item; float: none; } /*All subsequent sub menu levels offset after 1st level sub menu */ .suckertreemenu ul li ul li ul{ left: 159px; /* no need to change, as true value set by script */ top: 0; } /* Sub level menu links style */ .suckertreemenu ul li ul li a{ display: block; width: 160px; /*width of sub menu levels*/ color: navy; text-decoration: none; padding: 1px 5px; border: 1px solid #ccc; } .suckertreemenu ul li a:hover{ background-color: black; color: white; } /*Background image for top level menu list links */ .suckertreemenu .mainfoldericon{ background: #F3F3F3 url(media/arrow-down.gif) no-repeat center right; } /*Background image for subsequent level menu list links */ .suckertreemenu .subfoldericon{ background: #F3F3F3 url(media/arrow-right.gif) no-repeat center right; } * html p#iepara{ /*For a paragraph (if any) that immediately follows suckertree menu, add 1em top spacing between the two in IE*/ padding-top: 1em; } /* Holly Hack for IE \*/ * html .suckertreemenu ul li { float: left; height: 1%; } * html .suckertreemenu ul li a { height: 1%; } /* End */ EDITS: Hit post before I was ready, added css data.
-
Thanks, I found it. There was an old reference to a network resource that was unavailable to the server. When I tried to run the website on the server I got a meaningful error message that allowed me to find the problem. Thanks for the Help MTS
-
Error: 404 File or directory not found. Development Path = C:\Documents and Settings\mtskull\My Documents\Visual Studio 2008\Projects\Typhon_Tracking\Typhon_Tracking\Typh_Hx.aspx Server Path = C:\inetpub\wwwroot\TyphTrak\Typh_Hx.aspx
-
I have a web app that runs fine on the Dev Machine but, when run from a folder on the server it cannot find files in the code behind. When I run it locally I can find all files. On the server, any <a> redirects work file but I can not use Response.Redirect in the code behind. //in the aspx page the following always works... <a href="NextPage.aspx?SID=1234">Go To Next Page</a> //in the code behind the equivalent does not work on the server. // But does work on the development machine Response.Redirect("~/NextPage.aspx?SID=1234"); On the Server the pages are located in a subdirectory. Updating the redirect to include the sub dir also does not work. I.E. "/SubDir/NextPage.aspx?SID=1234" Not sure what else to try at the moment. Thanks MTS
-
How easy was that! I switched from session to Query String and passed the session variable as the value and presto it worked. Your help is greatly Appreciated.
-
I am trying to tie a sqlDatasource to a Stored Procedure. The stored procedure looks like... dbo.Select_SomeData_BySuperAssemID (@SuperAssemID as int) Select * From SomeTable Where SuperAssemID= @SuperAssemID Then the asp page is accessed via ... Response.Redirect("DataPage.aspx?SuperID=" + ID); In the code behind I can access and use Super ID no problem, but when I try to set up the SQL data source to access super ID it returns nothing. My gridview is bound to the following control. <asp:SqlDataSource ID="sqlSubAssemblies" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnStr %>" SelectCommand="Select_SomeData_BySuperID" SelectCommandType="StoredProcedure"> <SelectParameters> <asp:SessionParameter Name="SuperAssemID" SessionField="SuperID" Type="Int32" /> </SelectParameters> </asp:SqlDataSource> Thanks in advance... Brian
-
I found this tutorial which helped get me started. http://www.dotnetspider.com/AspNet-Tutorials.aspx
-
I need to design a web page that will link into an access database and allow data entry and viewing. I have extensive experience with Access, VB and C# but no experience with web apps. I have the option of handing this off, but would rather add a new tool to my skill set. So I need a over view of what I need to do to create and set up an ASP web page. With the overview I should be able to use Google and figure the details out for myself. Links to tutorials are also appreciated. Thanks MTS
-
I keep forgetting how slow string manip really is. I dropped you code into the function and it now runs "Instantly" on a 1 meg byte array. Thanks saved me from doing a bit more work. MTS
-
The least 8 bytes are used by the program. No Carries. Interesting, It worked on several different files for me. Maybe I posted the wrong one, in the original post. One problem I had with the original was I forgot to seed the random array generator so I would get a different file every time, and a different checksum. I was ready for nervous break down till i figured that one out. I just wanted it to work. Now that I know what I am doing I will look into optimizing it. On my machine with a one meg file there is a short but perceived lag. This is part one. I need to generate two CRC32 values for other files as well. I think that may be a bit easier though. Although this should have been as well, just over thinking the problem. Thanks MTS
-
Finally here is the correct algorithm UInt64 Sixteen_Bit_Checksum(byte[] Bytes, bool BigEndian) { UInt32 workingByte = 0x0; UInt64 sum = 0x0; string msByte = ""; // most significant byte string lsByte = ""; // least significant byte for (Int32 x = 0; x < Bytes.GetUpperBound(0); x += 2) { if (BigEndian == true) { // big endian so swap bytes msByte = Bytes[x + 1].ToString("X").PadLeft(2, (char)48); lsByte = Bytes[x].ToString("X").PadLeft(2, (char)48); } else // little endian, no swap { msByte = Bytes[x].ToString("X").PadLeft(2, (char)48); lsByte = Bytes[x + 1].ToString("X").PadLeft(2, (char)48); } workingByte = UInt32.Parse(msByte + lsByte, NumberStyles.HexNumber); sum += (UInt64)workingByte; } return sum; }
-
Part 2 of an earlier post. Going in a different direction. A vendor gave me some code to generate a checksum. I got the vendor code working and it does not even come close to returning the right value, so I suspect they did not understand what I was asking. It does generate a correct CRC 16 value but that is not what their program produces. If i can figure this out then I can automate one labor intensive process and eliminate a test further down the factory line. I found this tutorial for generating checksums at http://www.netfor2.com/checksum.html I used this to base my new algorithm on because I downloaded �010 Editor� by Sweetscape. It calculates various checksums for bin files. Running this against my hex file I find that it� generates a 16 bit Bigendian Checksum that equals the vendors correct checksum. Against the attached Random Binary File I get. I had to change the extension to .txt, changing it back to .bin should yield the same data. 010Editor Checksum, Ushort (16bit), Bigendian = 00000004 00162847 Vendor Value I am trying to Duplicate, generated by their manual software. Data Sumcheck Unswapped=162847 (same as above without the carry) My algorithm returns 16284B or 4 off the correct answer. Which, incidentally, is the same as the carry left over in the upper bytes from 010Editor. Here is the algorithm I developed. // following comments copied from http://www.netfor2.com/checksum.html //01 00 F2 03 F4 F5 F6 F7 00 00 //(00 00 is the checksum field) //Form the 16-bit words //0100 F203 F4F5 F6F7 //Calculate 2's complement sum //0100 + F203 + F4F5 + F6F7 = 0002 DEEF (store the sum in a 32-bit word) //Add the carries (0002) to get the 16-bit 1's complement sum //DEEF + 002 = DEF1 //Calculate 1's complement of the 1's complement sum //~DEF1 = 210E //We send the packet including the checksum 21 0E //01 00 F2 03 F4 F5 F6 F7 21 0E UInt32 OnesCompCheckSum_WCarry(byte[] Bytes) { // developed based on above comments UInt64 CheckSum = 0; // bigger to capture overflow in upper bytes UInt32 tempOnes = 0; string temp = ""; for (int x = 0; x < Bytes.GetUpperBound(0); x += 2) { //swapped //temp = Bytes[x + 1].ToString("X").PadLeft(2, (char)48); //temp += Bytes[x].ToString("X").PadLeft(2, (char)48); //unswapped // very close to desired temp = Bytes[x].ToString("X").PadLeft(2, (char)48); temp += Bytes[x + 1].ToString("X").PadLeft(2, (char)48); tempOnes = UInt32.Parse(temp, NumberStyles.HexNumber); tempOnes = ~tempOnes; CheckSum += tempOnes; } //add the carry back in. temp = CheckSum.ToString("X").PadLeft(16, (char)48); // check sum to 16byte hex string UInt32 Carry = UInt32.Parse(temp.Substring(0,8),NumberStyles.HexNumber); // first 8 hex chars, to int tempOnes = UInt32.Parse(temp.Substring(8), NumberStyles.HexNumber); // last 8 hex chars, to int tempOnes += Carry; CheckSum = ~tempOnes; //so I can set a break point and see what I am returning temp = CheckSum.ToString("X").PadLeft(16, (char)48); return ~(tempOnes); } RandImage.txt
-
I have tried your suggestions and several others and I am not getting any where close with this algorithm. So I am going to try a different approach.
-
I was given a set of functions in c or c++ that I need to convert to C# if possible. Background: I am automating a process that will take two hex formatted data files and merge them to create an aggregate memory map for a microprocessor. We have 30 to 40 active products and each has different firmware and initial data files, these files change on a regular basis and I don�t want to have to maintain the system. So I want to be able to create these files on the fly, so I can feed the updated file to the microprocessor programmer every time a batch of products is constructed. The manufacturer has several utilities to create the files but it is not easy to do with so many different products and changes to keep track of. I have the final files created by the process. I have completed the Binary Merge process and create the memory map files easily on the fly. The second part is a job text file that tells the preprogrammer what to do with the files. There are 2 CRCs that are generated and placed in job file. Here is where I am stuck. I can make an exact match for the mem map file but cannot generate an appropriate CRC. If I use my file and their program I get the correct CRC, so I know the Bin file generation is correct. What I need Help with: The vendor for the preprogrammer sent me a C? or C++? File that generates the CRC. I need, either a way to translate their code to C#, or a way to drop their code in to a library file that I can link to. In my program the bin file image is stored as a 1meg (1048576bytes) array. The vendors software looks like it takes a UInt32 pointer to the data array. Unfortunately the mem map is proprietary so I can not post it here. I do know the correct answer I am expecting and will post my attempts and the original source below. Original code from vendor� // Compute sumcheck on memory buffer of ULONGs by adding up the the buffer's data by // swapping the endian of each data element before adding it to the sum. // The WordWidth must be included since this method needs to know how the buffer is swapped (WORD or DWORD) DWORD DoSumcheckSwappedWithWidth( DWORD* pBuf, DWORD nBytes, WORD nWordWidth, DWORD nBeginValue /* =0 */ ) { DWORD nUnits = nBytes / sizeof(ULONG) + ( nBytes % sizeof(ULONG) ? 1 : 0 ); DWORD nSum = nBeginValue; while ( nUnits-- ) { // Perform a byte swap of the data when retrieving it from the buffer nSum += SwapEndian(*pBuf++, nWordWidth); } return nSum; } inline DWORD SwapEndian(DWORD dwData, WORD nWordWidth = 0) { DWORD dwResult; // Do normal 32 bit swap // Example: // Before: 01 02 03 04 // After: 04 03 02 01 if (nWordWidth != 16) { dwResult = dwData >> 24; dwResult |= ((dwData & 0x00FF0000) >> 8); dwResult |= ((dwData & 0x0000FF00) << 8); dwResult |= ((dwData & 0x000000FF) << 24); } // Swap endian of a 32 bit value in a 16 bit fashion. // This will do a WORD swap of the upper and lower WORDs in a DWORD. This is useful for // unswapping WORD swapped data when a 32 bit result is needed such as for calculating a 32 bit checksum // on a buffer of data that has been WORD swapped (and the unswapped checksum is desired). // Example: // Before: 01 02 03 04 // After: 02 01 04 03 else { dwResult = SwapEndian( HIWORD(dwData) ) << 16; dwResult |= SwapEndian( LOWORD(dwData) ); } return dwResult; } My C# translation attempt� public UInt32 CalcCheckSum(UInt32* pBuf, UInt32 nBytes, UInt16 nUInt16Width, UInt32 nBeginValue/* =0 */) { UInt32 nUnits = nBytes / sizeof(UInt64);// +(nBytes % sizeof(UInt64) ? 1 : 0); if ((nBytes % sizeof(UInt64)) == 0) nUnits++; UInt32 Counter = 0; UInt32 nSum = nBeginValue; while (nUnits >= 0) {// Perform a byte swap of the data when retrieving it from the buffer nSum += SwapEndian(*pBuf++, nUInt16Width); nUnits--; } return nSum; } UInt32 SwapEndian(UInt32 dwData, UInt16 nUInt16Width) //=0) { UInt32 dwResult; // Do normal 32 bit swap // Example: // Before: 01 02 03 04 // After: 04 03 02 01 if (nUInt16Width != 16) { dwResult = dwData >> 24; dwResult |= ((dwData & 0x00FF0000) >> 8); dwResult |= ((dwData & 0x0000FF00) << 8); dwResult |= ((dwData & 0x000000FF) << 24); } // Swap endian of a 32 bit value in a 16 bit fashion. // This will do a UInt16 swap of the upper and lower UInt16s in a UInt32. This is useful for // unswapping UInt16 swapped data when a 32 bit result is needed such as for calculating a 32 bit checksum // on a buffer of data that has been UInt16 swapped (and the unswapped checksum is desired). // Example: // Before: 01 02 03 04 // After: 02 01 04 03 else { dwResult = SwapEndian(HIUINT16(dwData), 0) << 16; dwResult |= SwapEndian(LOUINT16(dwData), 0); } return dwResult; } //Not sure if these are right??? UInt32 HIUINT16(UInt32 n) { return ((n)>>16); } UInt32 LOUINT16(UInt32 n) { return ((n)&0xFFFF); } Sorry for only posting hard stuff. And thanks for the help. MTS
-
Wow must be a tough one. Couple of updates in case anyone references this in the future. Baud Rate is Symbol Rate not gross BPS. So all of my calculations are based on symbol rate. After talking to the hardware engineers and them showing me the product fine print it is actually measured as Bits Per Second. So with the serial ports set to 1 start bit, 8 data bits and one space between symbols. We get ten bits per symbol. I ran the comports through a null modem into each other to check if I was getting any bottlenecks over the USB ports. I consistently measured right at 115200 Bps. I got similar results when I ran one USB port into the native serial port. So with that sorted I intend to introduce the test devices and see how that effects the results. Other then that the above code is a good rough frame work for bit throughput testing with some additional modifications. Modified above class constructor with... bytesToTransmit = (BaudRate * SecondsToTX) / 10; Later MTS
-
I am trying to create a throughput test. I have two data radios that I need to test at 115200 Baud and need to make sure the data arrives at better then 140000 Baud over a 3 second burst of random byte data. I am creating a randomized array size of Baud Rate * 3seconds, and then measuring the time it takes to get the data back, In addition I compare the data sent to the data received to check for errors. My current solution takes ~38 seconds to run, so I think part of the bottle neck is currently code based. I used a multithread transmit and receive solution. Where I transmit all of the data in one thread via one com port and then listen on another thread in another com port for the data. Both the TX and RX ports are set to 115200. Following is the class I use to setup and run the whole thing. What I need to know is can I make this work somehow. Or do I need to scrap this and find another solution. The com ports are USB serial port emulators, which might also be contributing to the problem. I also thought it might be better to write this as a library in C++ for better speed. I have a meeting with the hardware engineers to confirm if the baud rate spec is Bytes or Bits, but since baud rate is typically in symbols per second I think it is bytes. All of the data transmitted between radios is FM modulated ascii. Thanks as always MTS P.S. Keep in mind this is a rough prototype, but I was surprised at how slow it was, so did not want to put more effort into it if not necessary. using System; using System.Collections.Generic; using System.Text; using System.IO.Ports; using System.Threading; using mts_ErrorConstant; using mts_RandomNumberGen; using mts_Utilities; namespace mts_DataTest { class DataTest { #region Variables private SerialPort txPort; private SerialPort rxPort; private byte[] txBuffer = new byte[1]; private byte[] rxBuffer = new byte[1]; private int baudRate = 0; private int secsToTX = 0; private int bytesToTransmit = 0; private int dataErrors = -1; private DateTime txStart = DateTime.Now; private DateTime rxStop = DateTime.Now; private double transitTime = -1; // transit time in seconds #endregion #region Properties //read write properties public SerialPort TransmitPort { get { return txPort; } set { txPort = value; } } public SerialPort ReceivePort { get { return rxPort; } set { rxPort = value; } } public byte[] TransmitBuffer { get { return txBuffer; } set { txBuffer = value; } } public byte[] ReceiveBuffer { get { return rxBuffer; } set { rxBuffer = value; } } public int BaudRate { get { return baudRate; } set { baudRate = value; } } public int SecondsToTX { get { return secsToTX; } set { secsToTX = value; } } //read only properties public int BytesToTransmit {// read only get { return bytesToTransmit; } //set { bytesToTransmit = value; } } public int DataErrors { get { return dataErrors; } //set { dataErrors = value; } } public double TransitTime { get { return transitTime; } //set { transitTime = value; } } #endregion public DataTest() {// TODO fill this in } public DataTest(SerialPort TransmitSerialPort, SerialPort ReceiveSerialPort, int BaudRateToTest, int SecondsToTransmit) { TransmitPort = TransmitSerialPort; ReceivePort = ReceiveSerialPort; BaudRate = BaudRateToTest; SecondsToTX = SecondsToTransmit; bytesToTransmit = BaudRate * SecondsToTX; TransmitBuffer = new byte[bytesToTransmit]; ReceiveBuffer = new byte[bytesToTransmit]; FillTXBuffer(); } public void FillTXBuffer() { // Fill up the transmit buffer with random data RandomNumberGen RandomNum = new RandomNumberGen(); RandomNum.FillByteArray(txBuffer); } public Int32 DataThroughPutTest(ref int NumberOfErrors, ref double TransitTimeInSeconds) { Thread txThread = new Thread(new ThreadStart(TransmitByteData_Threaded)); Thread rxThread = new Thread(new ThreadStart(ReceiveByteData_Threaded)); txThread.Start(); rxThread.Start(); while (rxThread.IsAlive == true) { // add time out code here� } TimeSpan transTime = rxStop.Subtract(txStart); transitTime = transTime.TotalSeconds; return ErrorConstant.ERROR_GEN_PASS; } //Data Test MultiThread Functions private void TransmitByteData_Threaded() { //start the timer txStart = DateTime.Now; //transmit all data txPort.Write(txBuffer, 0, bytesToTransmit); } private void ReceiveByteData_Threaded() { string data = ""; Int32 loopCount = 0; // minimize what we do here for speed while (data.Length < bytesToTransmit && loopCount < 1000000) { // TODO time this instead of a blanket 1mil loop time out data += rxPort.ReadExisting(); loopCount++; } rxStop = DateTime.Now; // proccess the data into an array for (int x = 0; x < data.Length; x++) { rxBuffer[x] = Convert.ToByte(Convert.ToChar(data.Substring(x, 1))); } } } } [/Code]
-
Just wondering which (if any) might be better? Since there are at least 4 ways to build a string that I can think of off the top of my head. Simple String Building int val = 2112; string myString = "SomeValue " + val.ToString(); [/Code] string.Format (what I prefer for readability, especially with bigger string construction) [Code] int val = 2112; string myString = string.Format("SomeValue {0}", val); [/Code] or StringBuilder? or string.Concat(string, string...) or some other method I can't think of at the moment. I can think of possibly valid times when I might want to use anyone method over anouther but thought I would let the experts weigh in. For string arrays StringCollections are heck of Fast, is StringBuilder the speedy equivalent? Just some random StringBuilding related thoughts. MTS