Search Results

Search found 4466 results on 179 pages for 'invalid'.

Page 19/179 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • Using AES encryption in .NET - CryptographicException saying the padding is invalid and cannot be removed

    - by Jake Petroules
    I wrote some AES encryption code in C# and I am having trouble getting it to encrypt and decrypt properly. If I enter "test" as the passphrase and "This data must be kept secret from everyone!" I receive the following exception: System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed. at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast) at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount) at System.Security.Cryptography.CryptoStream.FlushFinalBlock() at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing) at System.IO.Stream.Close() at System.IO.Stream.Dispose() ... And if I enter something less than 16 characters I get no output. I believe I need some special handling in the encryption since AES is a block cipher, but I'm not sure exactly what that is, and I wasn't able to find any examples on the web showing how. Here is my code: using System; using System.IO; using System.Security.Cryptography; using System.Text; public static class DatabaseCrypto { public static EncryptedData Encrypt(string password, string data) { return DatabaseCrypto.Transform(true, password, data, null, null) as EncryptedData; } public static string Decrypt(string password, EncryptedData data) { return DatabaseCrypto.Transform(false, password, data.DataString, data.SaltString, data.MACString) as string; } private static object Transform(bool encrypt, string password, string data, string saltString, string macString) { using (AesManaged aes = new AesManaged()) { aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; int key_len = aes.KeySize / 8; int iv_len = aes.BlockSize / 8; const int salt_size = 8; const int iterations = 8192; byte[] salt = encrypt ? new Rfc2898DeriveBytes(string.Empty, salt_size).Salt : Convert.FromBase64String(saltString); byte[] bc_key = new Rfc2898DeriveBytes("BLK" + password, salt, iterations).GetBytes(key_len); byte[] iv = new Rfc2898DeriveBytes("IV" + password, salt, iterations).GetBytes(iv_len); byte[] mac_key = new Rfc2898DeriveBytes("MAC" + password, salt, iterations).GetBytes(16); aes.Key = bc_key; aes.IV = iv; byte[] rawData = encrypt ? Encoding.UTF8.GetBytes(data) : Convert.FromBase64String(data); using (ICryptoTransform transform = encrypt ? aes.CreateEncryptor() : aes.CreateDecryptor()) using (MemoryStream memoryStream = encrypt ? new MemoryStream() : new MemoryStream(rawData)) using (CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, encrypt ? CryptoStreamMode.Write : CryptoStreamMode.Read)) { if (encrypt) { cryptoStream.Write(rawData, 0, rawData.Length); return new EncryptedData(salt, mac_key, memoryStream.ToArray()); } else { byte[] originalData = new byte[rawData.Length]; int count = cryptoStream.Read(originalData, 0, originalData.Length); return Encoding.UTF8.GetString(originalData, 0, count); } } } } } public class EncryptedData { public EncryptedData() { } public EncryptedData(byte[] salt, byte[] mac, byte[] data) { this.Salt = salt; this.MAC = mac; this.Data = data; } public EncryptedData(string salt, string mac, string data) { this.SaltString = salt; this.MACString = mac; this.DataString = data; } public byte[] Salt { get; set; } public string SaltString { get { return Convert.ToBase64String(this.Salt); } set { this.Salt = Convert.FromBase64String(value); } } public byte[] MAC { get; set; } public string MACString { get { return Convert.ToBase64String(this.MAC); } set { this.MAC = Convert.FromBase64String(value); } } public byte[] Data { get; set; } public string DataString { get { return Convert.ToBase64String(this.Data); } set { this.Data = Convert.FromBase64String(value); } } } static void ReadTest() { Console.WriteLine("Enter password: "); string password = Console.ReadLine(); using (StreamReader reader = new StreamReader("aes.cs.txt")) { EncryptedData enc = new EncryptedData(); enc.SaltString = reader.ReadLine(); enc.MACString = reader.ReadLine(); enc.DataString = reader.ReadLine(); Console.WriteLine("The decrypted data was: " + DatabaseCrypto.Decrypt(password, enc)); } } static void WriteTest() { Console.WriteLine("Enter data: "); string data = Console.ReadLine(); Console.WriteLine("Enter password: "); string password = Console.ReadLine(); EncryptedData enc = DatabaseCrypto.Encrypt(password, data); using (StreamWriter stream = new StreamWriter("aes.cs.txt")) { stream.WriteLine(enc.SaltString); stream.WriteLine(enc.MACString); stream.WriteLine(enc.DataString); Console.WriteLine("The encrypted data was: " + enc.DataString); } }

    Read the article

  • ruby on rails language problem "invalid byte sequence in GBK"

    - by user357203
    This is definitely a language issue, both of our code and our database contains Chinese characters. **This is my environment: About your application's environment Ruby version 1.9.1 (i386-mingw32) RubyGems version 1.3.5 Rack version 1.0 Rails version 2.3.5 Active Record version 2.3.5 Active Resource version 2.3.5 Action Mailer version 2.3.5 Active Support version 2.3.5 Application root C:/path_to_my_root Environment development Database adapter mysql Database schema version 20100327010640 **This is my localhost;3000 after running my ruby server: ArgumentError in HomeController#construction invalid byte sequence in GBK RAILS_ROOT: C:/path_to_my_root Application Trace | Framework Trace | Full Trace C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/action_view/ template_error.rb:43:in `split' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/action_view/ template_error.rb:43:in `source_extract' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/action_view/ template_error.rb:86:in `compute_backtrace' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/action_view/ template_error.rb:11:in `initialize' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/action_view/ template.rb:212:in `new' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/action_view/ template.rb:212:in `rescue in render_template' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/action_view/ template.rb:205:in `render_template' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/action_view/ base.rb:265:in `render' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/action_view/ base.rb:352:in `_render_with_layout' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/action_view/ base.rb:262:in `render' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/base.rb:1250:in `render_for_file' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/base.rb:951:in `render' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/benchmarking.rb:51:in `block in render_with_benchmark' C:/Ruby19/lib/ruby/gems/1.9.1/gems/activesupport-2.3.5/lib/ active_support/core_ext/benchmark.rb:17:in `block in ms' C:/Ruby19/lib/ruby/1.9.1/benchmark.rb:309:in `realtime' C:/Ruby19/lib/ruby/gems/1.9.1/gems/activesupport-2.3.5/lib/ active_support/core_ext/benchmark.rb:17:in `ms' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/benchmarking.rb:51:in `render_with_benchmark' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/mime_responds.rb:135:in `block in custom' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/mime_responds.rb:179:in `call' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/mime_responds.rb:179:in `block in respond' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/mime_responds.rb:173:in `each' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/mime_responds.rb:173:in `respond' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/mime_responds.rb:107:in `respond_to' C:/Users/Howard/Documents/local/vjoin/app/controllers/ home_controller.rb:53:in `construction' ..... C:/Ruby19/lib/ruby/gems/1.9.1/gems/rack-1.0.1/lib/rack/ methodoverride.rb:24:in `call' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/params_parser.rb:15:in `call' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/session/cookie_store.rb:93:in `call' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/failsafe.rb:26:in `call' C:/Ruby19/lib/ruby/gems/1.9.1/gems/rack-1.0.1/lib/rack/lock.rb:11:in `block in call' :8:in `synchronize' C:/Ruby19/lib/ruby/gems/1.9.1/gems/rack-1.0.1/lib/rack/lock.rb:11:in `call' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/dispatcher.rb:114:in `block in call' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/reloader.rb:34:in `run' C:/Ruby19/lib/ruby/gems/1.9.1/gems/actionpack-2.3.5/lib/ action_controller/dispatcher.rb:108:in `call' C:/Ruby19/lib/ruby/gems/1.9.1/gems/rails-2.3.5/lib/rails/rack/ static.rb:31:in `call' C:/Ruby19/lib/ruby/gems/1.9.1/gems/rack-1.0.1/lib/rack/urlmap.rb:46:in `block in call' C:/Ruby19/lib/ruby/gems/1.9.1/gems/rack-1.0.1/lib/rack/urlmap.rb:40:in `each' C:/Ruby19/lib/ruby/gems/1.9.1/gems/rack-1.0.1/lib/rack/urlmap.rb:40:in `call' C:/Ruby19/lib/ruby/gems/1.9.1/gems/rails-2.3.5/lib/rails/rack/ log_tailer.rb:17:in `call' C:/Ruby19/lib/ruby/gems/1.9.1/gems/rack-1.0.1/lib/rack/ content_length.rb:13:in `call' C:/Ruby19/lib/ruby/gems/1.9.1/gems/rack-1.0.1/lib/rack/handler/ webrick.rb:50:in `service' C:/Ruby19/lib/ruby/1.9.1/webrick/httpserver.rb:111:in `service' C:/Ruby19/lib/ruby/1.9.1/webrick/httpserver.rb:70:in `run' C:/Ruby19/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread' Request Parameters: None Show session dump Response Headers: {"Cache-Control"=>"no-cache", "Content-Type"=>"text/html"} **What should I do? I tried to search online, didn't find much. The only thing I found was something like putting the following into application_controller: before_filter :set_charset, :set_locale def set_charset response.headers["Content-Type"] = "text/html; charset=utf-8" WIN32OLE.codepage = WIN32OLE::CP_UTF8 end but this still doesn't work. I am new to ruby on rails, so don't know much about it. Thanks for your help.

    Read the article

  • Invalid function declaration. DevC++

    - by user69514
    Why do I get invalid function declaration when I compile the code in DevC++ in Windows, but when I compile it in CodeBlocks on Linux it works fine. #include <iostream> #include <vector> using namespace std; //structure to hold item information struct item{ string name; double price; }; //define sandwich, chips, and drink struct item sandwich{"Sandwich", 3.00}; **** error is here ***** struct item chips{"Chips", 1.50}; **** error is here ***** struct item drink{"Large Drink", 2.00}; **** error is here ***** vector<item> cart; //vector to hold the items double total = 0.0; //total const double tax = 0.0825; //tax //gets item choice from user char getChoice(){ cout << "Select an item:" << endl; cout << "S: Sandwich. $3.00" << endl; cout << "C: Chips. $1.50" << endl; cout << "D: Drink. $2.00" << endl; cout << "X: Cancel. Start over" << endl; cout << "T: Total" << endl; char choice; cin >> choice; return choice; } //displays current items in cart and total void displayCart(){ cout << "\nCart:" << endl; for(unsigned int i=0; i<cart.size(); i++){ cout << cart.at(i).name << ". $" << cart.at(i).price << endl; } cout << "Total: $" << total << endl << endl; } //adds item to the cart void addItem(struct item bought){ cart.push_back(bought); total += bought.price; displayCart(); } //displays the receipt, items, prices, subtotal, taxes, and total void displayReceipt(){ cout << "\nReceipt:" << endl; cout << "Items: " << cart.size() << endl; for(unsigned int i=0; i<cart.size(); i++){ cout << (i+1) << ". " << cart.at(i).name << ". $" << cart.at(i).price << endl; } cout << "----------------------------" << endl; cout << "Subtotal: $" << total << endl; double taxes = total*tax; cout << "Tax: $" << taxes << endl; cout << "Total: $" << (total + taxes) << endl; } int main(){ //sentinel to stop the loop bool stop = false; char choice; while (stop == false ){ choice = getChoice(); //add sandwich if( choice == 's' || choice == 'S' ){ addItem(sandwich); } //add chips else if( choice == 'c' || choice == 'C' ){ addItem(chips); } //add drink else if( choice == 'd' || choice == 'D' ){ addItem(drink); } //remove everything from cart else if( choice == 'x' || choice == 'X' ){ cart.clear(); total = 0.0; cout << "\n***** Transcation Canceled *****\n" << endl; } //calcualte total else if( choice == 't' || choice == 'T' ){ displayReceipt(); stop = true; } //or wront item picked else{ cout << choice << " is not a valid choice. Try again\n" << endl; } }//end while loop return 0; //end of program }

    Read the article

  • Dataset.ReadXml() - Invalid character in the given encoding

    - by NLV
    Hello all I have saved a dataset in the sql database in an xml column using the following code. XmlDataDocument dd = new XmlDataDocument(dataset); and passing this xml document as sql parameter using param.value = new XmlNodeReader(dd); The XML is like <NewDataSet><SubContractChangeOrders><AGCol>1</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>006</Contract_x0020_Number><ContractID>30</ContractID><ChangeOrderID>211</ChangeOrderID><Amount>0.0000</Amount><Udf_CostReimbursableFlag>false</Udf_CostReimbursableFlag><Udf_CustomerCode /><Udf_SubChangeOrderStatus /></SubContractChangeOrders><SubContractChangeOrders><AGCol>2</AGCol><SCO_x0020_Number>002</SCO_x0020_Number><Contract_x0020_Number>006</Contract_x0020_Number><ContractID>30</ContractID><ChangeOrderID>212</ChangeOrderID><Amount>0.0000</Amount><Udf_CostReimbursableFlag>false</Udf_CostReimbursableFlag></SubContractChangeOrders><SubContractChangeOrders><AGCol>3</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>111</Contract_x0020_Number><ContractID>87</ContractID><ChangeOrderID>12</ChangeOrderID><Amount>300.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>4</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>222</Contract_x0020_Number><ContractID>80</ContractID><ChangeOrderID>6</ChangeOrderID><Amount>100.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>5</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>777</Contract_x0020_Number><ContractID>79</ContractID><ChangeOrderID>5</ChangeOrderID><Amount>200.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>6</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>786</Contract_x0020_Number><ContractID>77</ContractID><ChangeOrderID>3</ChangeOrderID><Amount>100.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>7</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>787</Contract_x0020_Number><ContractID>78</ContractID><ChangeOrderID>4</ChangeOrderID><Amount>500.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>8</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con 009</Contract_x0020_Number><ContractID>219</ContractID><ChangeOrderID>78</ChangeOrderID><Amount>9000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>9</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con 010</Contract_x0020_Number><ContractID>220</ContractID><ChangeOrderID>79</ChangeOrderID><Amount>13000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>10</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con 012</Contract_x0020_Number><ContractID>222</ContractID><ChangeOrderID>83</ChangeOrderID><Amount>2300.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>11</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con 020</Contract_x0020_Number><ContractID>226</ContractID><ChangeOrderID>86</ChangeOrderID><Amount>5400.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>12</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con 021</Contract_x0020_Number><ContractID>227</ContractID><ChangeOrderID>87</ChangeOrderID><Amount>2300.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>13</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con001</Contract_x0020_Number><ContractID>208</ContractID><ChangeOrderID>72</ChangeOrderID><Amount>3000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>14</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con002</Contract_x0020_Number><ContractID>209</ContractID><ChangeOrderID>73</ChangeOrderID><Amount>400.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>15</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con003</Contract_x0020_Number><ContractID>210</ContractID><ChangeOrderID>74</ChangeOrderID><Amount>6000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>16</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con004</Contract_x0020_Number><ContractID>211</ContractID><ChangeOrderID>75</ChangeOrderID><Amount>9000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>17</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Con005</Contract_x0020_Number><ContractID>213</ContractID><ChangeOrderID>76</ChangeOrderID><Amount>17000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>18</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>Cont001</Contract_x0020_Number><ContractID>228</ContractID><ChangeOrderID>89</ChangeOrderID><Amount>2000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>19</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>PUR001</Contract_x0020_Number><ContractID>229</ContractID><ChangeOrderID>88</ChangeOrderID><Amount>1000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>20</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>PUR002</Contract_x0020_Number><ContractID>230</ContractID><ChangeOrderID>90</ChangeOrderID><Amount>3000.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>21</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>SC-002</Contract_x0020_Number><ContractID>2</ContractID><ChangeOrderID>7</ChangeOrderID><Amount>200.0000</Amount></SubContractChangeOrders><SubContractChangeOrders><AGCol>22</AGCol><SCO_x0020_Number>001</SCO_x0020_Number><Contract_x0020_Number>SC-004</Contract_x0020_Number><ContractID>7</ContractID><ChangeOrderID>65</ChangeOrderID><Amount>1000.0000</Amount></SubContractChangeOrders></NewDataSet> I'm trying to read it back as follows using (SqlConnection con = new SqlConnection("Server=#####;Initial Catalog=#####;User ID=####;Pwd=########")) { using (SqlCommand com = new SqlCommand("select * from dbo.tbl_#####", con)) { using (SqlDataAdapter ada = new SqlDataAdapter(com)) { ada.Fill(dt); MemoryStream ms = new MemoryStream(); object contractXML1 = dt.Rows[0]["SCOXML1"]; System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(ms, contractXML1); ms.Seek(0, SeekOrigin.Begin); ds.ReadXml(ms); } } } I'm getting the following error Data at the root level is invalid. Line 1, position 6. Any ideas? NLV

    Read the article

  • Invalid algorithm specified on Windows 2003 Server only

    - by JL
    I am decoding a file using the following method: string outFileName = zfoFileName.Replace(".zfo", "_tmp.zfo"); FileStream inFile = null; FileStream outFile = null; inFile = File.Open(zfoFileName, FileMode.Open); outFile = File.Create(outFileName); LargeCMS.CMS cms = new LargeCMS.CMS(); cms.Decode(inFile, outFile); This is working fine on my Win 7 dev machine, but on a Windows 2003 server production machine it fails with the following exception: Exception: System.Exception: CryptMsgUpdate error #-2146893816 --- System.ComponentModel.Win32Exception: Invalid algorithm specified --- End of inner exception stack trace --- at LargeCMS.CMS.Decode(FileStream inFile, FileStream outFile) Here are the classes below which I call to do the decoding, if needed I can upload a sample file for decoding, its just strange it works on Win 7, and not on Win2k3 server: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Runtime.InteropServices; using System.ComponentModel; namespace LargeCMS { class CMS { // File stream to use in callback function private FileStream m_callbackFile; // Streaming callback function for encoding private Boolean StreamOutputCallback(IntPtr pvArg, IntPtr pbData, int cbData, Boolean fFinal) { // Write all bytes to encoded file Byte[] bytes = new Byte[cbData]; Marshal.Copy(pbData, bytes, 0, cbData); m_callbackFile.Write(bytes, 0, cbData); if (fFinal) { // This is the last piece. Close the file m_callbackFile.Flush(); m_callbackFile.Close(); m_callbackFile = null; } return true; } // Encode CMS with streaming to support large data public void Encode(X509Certificate2 cert, FileStream inFile, FileStream outFile) { // Variables Win32.CMSG_SIGNER_ENCODE_INFO SignerInfo; Win32.CMSG_SIGNED_ENCODE_INFO SignedInfo; Win32.CMSG_STREAM_INFO StreamInfo; Win32.CERT_CONTEXT[] CertContexts = null; Win32.BLOB[] CertBlobs; X509Chain chain = null; X509ChainElement[] chainElements = null; X509Certificate2[] certs = null; RSACryptoServiceProvider key = null; BinaryReader stream = null; GCHandle gchandle = new GCHandle(); IntPtr hProv = IntPtr.Zero; IntPtr SignerInfoPtr = IntPtr.Zero; IntPtr CertBlobsPtr = IntPtr.Zero; IntPtr hMsg = IntPtr.Zero; IntPtr pbPtr = IntPtr.Zero; Byte[] pbData; int dwFileSize; int dwRemaining; int dwSize; Boolean bResult = false; try { // Get data to encode dwFileSize = (int)inFile.Length; stream = new BinaryReader(inFile); pbData = stream.ReadBytes(dwFileSize); // Prepare stream for encoded info m_callbackFile = outFile; // Get cert chain chain = new X509Chain(); chain.Build(cert); chainElements = new X509ChainElement[chain.ChainElements.Count]; chain.ChainElements.CopyTo(chainElements, 0); // Get certs in chain certs = new X509Certificate2[chainElements.Length]; for (int i = 0; i < chainElements.Length; i++) { certs[i] = chainElements[i].Certificate; } // Get context of all certs in chain CertContexts = new Win32.CERT_CONTEXT[certs.Length]; for (int i = 0; i < certs.Length; i++) { CertContexts[i] = (Win32.CERT_CONTEXT)Marshal.PtrToStructure(certs[i].Handle, typeof(Win32.CERT_CONTEXT)); } // Get cert blob of all certs CertBlobs = new Win32.BLOB[CertContexts.Length]; for (int i = 0; i < CertContexts.Length; i++) { CertBlobs[i].cbData = CertContexts[i].cbCertEncoded; CertBlobs[i].pbData = CertContexts[i].pbCertEncoded; } // Get CSP of client certificate key = (RSACryptoServiceProvider)certs[0].PrivateKey; bResult = Win32.CryptAcquireContext( ref hProv, key.CspKeyContainerInfo.KeyContainerName, key.CspKeyContainerInfo.ProviderName, key.CspKeyContainerInfo.ProviderType, 0 ); if (!bResult) { throw new Exception("CryptAcquireContext error #" + Marshal.GetLastWin32Error().ToString(), new Win32Exception(Marshal.GetLastWin32Error())); } // Populate Signer Info struct SignerInfo = new Win32.CMSG_SIGNER_ENCODE_INFO(); SignerInfo.cbSize = Marshal.SizeOf(SignerInfo); SignerInfo.pCertInfo = CertContexts[0].pCertInfo; SignerInfo.hCryptProvOrhNCryptKey = hProv; SignerInfo.dwKeySpec = (int)key.CspKeyContainerInfo.KeyNumber; SignerInfo.HashAlgorithm.pszObjId = Win32.szOID_OIWSEC_sha1; // Populate Signed Info struct SignedInfo = new Win32.CMSG_SIGNED_ENCODE_INFO(); SignedInfo.cbSize = Marshal.SizeOf(SignedInfo); SignedInfo.cSigners = 1; SignerInfoPtr = Marshal.AllocHGlobal(Marshal.SizeOf(SignerInfo)); Marshal.StructureToPtr(SignerInfo, SignerInfoPtr, false); SignedInfo.rgSigners = SignerInfoPtr; SignedInfo.cCertEncoded = CertBlobs.Length; CertBlobsPtr = Marshal.AllocHGlobal(Marshal.SizeOf(CertBlobs[0]) * CertBlobs.Length); for (int i = 0; i < CertBlobs.Length; i++) { Marshal.StructureToPtr(CertBlobs[i], new IntPtr(CertBlobsPtr.ToInt64() + (Marshal.SizeOf(CertBlobs[i]) * i)), false); } SignedInfo.rgCertEncoded = CertBlobsPtr; // Populate Stream Info struct StreamInfo = new Win32.CMSG_STREAM_INFO(); StreamInfo.cbContent = dwFileSize; StreamInfo.pfnStreamOutput = new Win32.StreamOutputCallbackDelegate(StreamOutputCallback); // TODO: CMSG_DETACHED_FLAG // Open message to encode hMsg = Win32.CryptMsgOpenToEncode( Win32.X509_ASN_ENCODING | Win32.PKCS_7_ASN_ENCODING, 0, Win32.CMSG_SIGNED, ref SignedInfo, null, ref StreamInfo ); if (hMsg.Equals(IntPtr.Zero)) { throw new Exception("CryptMsgOpenToEncode error #" + Marshal.GetLastWin32Error().ToString(), new Win32Exception(Marshal.GetLastWin32Error())); } // Process the whole message gchandle = GCHandle.Alloc(pbData, GCHandleType.Pinned); pbPtr = gchandle.AddrOfPinnedObject(); dwRemaining = dwFileSize; dwSize = (dwFileSize < 1024 * 1000 * 100) ? dwFileSize : 1024 * 1000 * 100; while (dwRemaining > 0) { // Update message piece by piece bResult = Win32.CryptMsgUpdate( hMsg, pbPtr, dwSize, (dwRemaining <= dwSize) ? true : false ); if (!bResult) { throw new Exception("CryptMsgUpdate error #" + Marshal.GetLastWin32Error().ToString(), new Win32Exception(Marshal.GetLastWin32Error())); } // Move to the next piece pbPtr = new IntPtr(pbPtr.ToInt64() + dwSize); dwRemaining -= dwSize; if (dwRemaining < dwSize) { dwSize = dwRemaining; } } } finally { // Clean up if (gchandle.IsAllocated) { gchandle.Free(); } if (stream != null) { stream.Close(); } if (m_callbackFile != null) { m_callbackFile.Close(); } if (!CertBlobsPtr.Equals(IntPtr.Zero)) { Marshal.FreeHGlobal(CertBlobsPtr); } if (!SignerInfoPtr.Equals(IntPtr.Zero)) { Marshal.FreeHGlobal(SignerInfoPtr); } if (!hProv.Equals(IntPtr.Zero)) { Win32.CryptReleaseContext(hProv, 0); } if (!hMsg.Equals(IntPtr.Zero)) { Win32.CryptMsgClose(hMsg); } } } // Decode CMS with streaming to support large data public void Decode(FileStream inFile, FileStream outFile) { // Variables Win32.CMSG_STREAM_INFO StreamInfo; Win32.CERT_CONTEXT SignerCertContext; BinaryReader stream = null; GCHandle gchandle = new GCHandle(); IntPtr hMsg = IntPtr.Zero; IntPtr pSignerCertInfo = IntPtr.Zero; IntPtr pSignerCertContext = IntPtr.Zero; IntPtr pbPtr = IntPtr.Zero; IntPtr hStore = IntPtr.Zero; Byte[] pbData; Boolean bResult = false; int dwFileSize; int dwRemaining; int dwSize; int cbSignerCertInfo; try { // Get data to decode dwFileSize = (int)inFile.Length; stream = new BinaryReader(inFile); pbData = stream.ReadBytes(dwFileSize); // Prepare stream for decoded info m_callbackFile = outFile; // Populate Stream Info struct StreamInfo = new Win32.CMSG_STREAM_INFO(); StreamInfo.cbContent = dwFileSize; StreamInfo.pfnStreamOutput = new Win32.StreamOutputCallbackDelegate(StreamOutputCallback); // Open message to decode hMsg = Win32.CryptMsgOpenToDecode( Win32.X509_ASN_ENCODING | Win32.PKCS_7_ASN_ENCODING, 0, 0, IntPtr.Zero, IntPtr.Zero, ref StreamInfo ); if (hMsg.Equals(IntPtr.Zero)) { throw new Exception("CryptMsgOpenToDecode error #" + Marshal.GetLastWin32Error().ToString(), new Win32Exception(Marshal.GetLastWin32Error())); } // Process the whole message gchandle = GCHandle.Alloc(pbData, GCHandleType.Pinned); pbPtr = gchandle.AddrOfPinnedObject(); dwRemaining = dwFileSize; dwSize = (dwFileSize < 1024 * 1000 * 100) ? dwFileSize : 1024 * 1000 * 100; while (dwRemaining > 0) { // Update message piece by piece bResult = Win32.CryptMsgUpdate( hMsg, pbPtr, dwSize, (dwRemaining <= dwSize) ? true : false ); if (!bResult) { throw new Exception("CryptMsgUpdate error #" + Marshal.GetLastWin32Error().ToString(), new Win32Exception(Marshal.GetLastWin32Error())); } // Move to the next piece pbPtr = new IntPtr(pbPtr.ToInt64() + dwSize); dwRemaining -= dwSize; if (dwRemaining < dwSize) { dwSize = dwRemaining; } } // Get signer certificate info cbSignerCertInfo = 0; bResult = Win32.CryptMsgGetParam( hMsg, Win32.CMSG_SIGNER_CERT_INFO_PARAM, 0, IntPtr.Zero, ref cbSignerCertInfo ); if (!bResult) { throw new Exception("CryptMsgGetParam error #" + Marshal.GetLastWin32Error().ToString(), new Win32Exception(Marshal.GetLastWin32Error())); } pSignerCertInfo = Marshal.AllocHGlobal(cbSignerCertInfo); bResult = Win32.CryptMsgGetParam( hMsg, Win32.CMSG_SIGNER_CERT_INFO_PARAM, 0, pSignerCertInfo, ref cbSignerCertInfo ); if (!bResult) { throw new Exception("CryptMsgGetParam error #" + Marshal.GetLastWin32Error().ToString(), new Win32Exception(Marshal.GetLastWin32Error())); } // Open a cert store in memory with the certs from the message hStore = Win32.CertOpenStore( Win32.CERT_STORE_PROV_MSG, Win32.X509_ASN_ENCODING | Win32.PKCS_7_ASN_ENCODING, IntPtr.Zero, 0, hMsg ); if (hStore.Equals(IntPtr.Zero)) { throw new Exception("CertOpenStore error #" + Marshal.GetLastWin32Error().ToString(), new Win32Exception(Marshal.GetLastWin32Error())); } // Find the signer's cert in the store pSignerCertContext = Win32.CertGetSubjectCertificateFromStore( hStore, Win32.X509_ASN_ENCODING | Win32.PKCS_7_ASN_ENCODING, pSignerCertInfo ); if (pSignerCertContext.Equals(IntPtr.Zero)) { throw new Exception("CertGetSubjectCertificateFromStore error #" + Marshal.GetLastWin32Error().ToString(), new Win32Exception(Marshal.GetLastWin32Error())); } // Set message for verifying SignerCertContext = (Win32.CERT_CONTEXT)Marshal.PtrToStructure(pSignerCertContext, typeof(Win32.CERT_CONTEXT)); bResult = Win32.CryptMsgControl( hMsg, 0, Win32.CMSG_CTRL_VERIFY_SIGNATURE, SignerCertContext.pCertInfo ); if (!bResult) { throw new Exception("CryptMsgControl error #" + Marshal.GetLastWin32Error().ToString(), new Win32Exception(Marshal.GetLastWin32Error())); } } finally { // Clean up if (gchandle.IsAllocated) { gchandle.Free(); } if (!pSignerCertContext.Equals(IntPtr.Zero)) { Win32.CertFreeCertificateContext(pSignerCertContext); } if (!pSignerCertInfo.Equals(IntPtr.Zero)) { Marshal.FreeHGlobal(pSignerCertInfo); } if (!hStore.Equals(IntPtr.Zero)) { Win32.CertCloseStore(hStore, Win32.CERT_CLOSE_STORE_FORCE_FLAG); } if (stream != null) { stream.Close(); } if (m_callbackFile != null) { m_callbackFile.Close(); } if (!hMsg.Equals(IntPtr.Zero)) { Win32.CryptMsgClose(hMsg); } } } } } and using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.ComponentModel; using System.Security.Cryptography; namespace LargeCMS { class Win32 { #region "CONSTS" public const int X509_ASN_ENCODING = 0x00000001; public const int PKCS_7_ASN_ENCODING = 0x00010000; public const int CMSG_SIGNED = 2; public const int CMSG_DETACHED_FLAG = 0x00000004; public const int AT_KEYEXCHANGE = 1; public const int AT_SIGNATURE = 2; public const String szOID_OIWSEC_sha1 = "1.3.14.3.2.26"; public const int CMSG_CTRL_VERIFY_SIGNATURE = 1; public const int CMSG_CERT_PARAM = 12; public const int CMSG_SIGNER_CERT_INFO_PARAM = 7; public const int CERT_STORE_PROV_MSG = 1; public const int CERT_CLOSE_STORE_FORCE_FLAG = 1; #endregion #region "STRUCTS" [StructLayout(LayoutKind.Sequential)] public struct CRYPT_ALGORITHM_IDENTIFIER { public String pszObjId; BLOB Parameters; } [StructLayout(LayoutKind.Sequential)] public struct CERT_ID { public int dwIdChoice; public BLOB IssuerSerialNumberOrKeyIdOrHashId; } [StructLayout(LayoutKind.Sequential)] public struct CMSG_SIGNER_ENCODE_INFO { public int cbSize; public IntPtr pCertInfo; public IntPtr hCryptProvOrhNCryptKey; public int dwKeySpec; public CRYPT_ALGORITHM_IDENTIFIER HashAlgorithm; public IntPtr pvHashAuxInfo; public int cAuthAttr; public IntPtr rgAuthAttr; public int cUnauthAttr; public IntPtr rgUnauthAttr; public CERT_ID SignerId; public CRYPT_ALGORITHM_IDENTIFIER HashEncryptionAlgorithm; public IntPtr pvHashEncryptionAuxInfo; } [StructLayout(LayoutKind.Sequential)] public struct CERT_CONTEXT { public int dwCertEncodingType; public IntPtr pbCertEncoded; public int cbCertEncoded; public IntPtr pCertInfo; public IntPtr hCertStore; } [StructLayout(LayoutKind.Sequential)] public struct BLOB { public int cbData; public IntPtr pbData; } [StructLayout(LayoutKind.Sequential)] public struct CMSG_SIGNED_ENCODE_INFO { public int cbSize; public int cSigners; public IntPtr rgSigners; public int cCertEncoded; public IntPtr rgCertEncoded; public int cCrlEncoded; public IntPtr rgCrlEncoded; public int cAttrCertEncoded; public IntPtr rgAttrCertEncoded; } [StructLayout(LayoutKind.Sequential)] public struct CMSG_STREAM_INFO { public int cbContent; public StreamOutputCallbackDelegate pfnStreamOutput; public IntPtr pvArg; } #endregion #region "DELEGATES" public delegate Boolean StreamOutputCallbackDelegate(IntPtr pvArg, IntPtr pbData, int cbData, Boolean fFinal); #endregion #region "API" [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern Boolean CryptAcquireContext( ref IntPtr hProv, String pszContainer, String pszProvider, int dwProvType, int dwFlags ); [DllImport("Crypt32.dll", SetLastError = true)] public static extern IntPtr CryptMsgOpenToEncode( int dwMsgEncodingType, int dwFlags, int dwMsgType, ref CMSG_SIGNED_ENCODE_INFO pvMsgEncodeInfo, String pszInnerContentObjID, ref CMSG_STREAM_INFO pStreamInfo ); [DllImport("Crypt32.dll", SetLastError = true)] public static extern IntPtr CryptMsgOpenToDecode( int dwMsgEncodingType, int dwFlags, int dwMsgType, IntPtr hCryptProv, IntPtr pRecipientInfo, ref CMSG_STREAM_INFO pStreamInfo ); [DllImport("Crypt32.dll", SetLastError = true)] public static extern Boolean CryptMsgClose( IntPtr hCryptMsg ); [DllImport("Crypt32.dll", SetLastError = true)] public static extern Boolean CryptMsgUpdate( IntPtr hCryptMsg, Byte[] pbData, int cbData, Boolean fFinal ); [DllImport("Crypt32.dll", SetLastError = true)] public static extern Boolean CryptMsgUpdate( IntPtr hCryptMsg, IntPtr pbData, int cbData, Boolean fFinal ); [DllImport("Crypt32.dll", SetLastError = true)] public static extern Boolean CryptMsgGetParam( IntPtr hCryptMsg, int dwParamType, int dwIndex, IntPtr pvData, ref int pcbData ); [DllImport("Crypt32.dll", SetLastError = true)] public static extern Boolean CryptMsgControl( IntPtr hCryptMsg, int dwFlags, int dwCtrlType, IntPtr pvCtrlPara ); [DllImport("advapi32.dll", SetLastError = true)] public static extern Boolean CryptReleaseContext( IntPtr hProv, int dwFlags ); [DllImport("Crypt32.dll", SetLastError = true)] public static extern IntPtr CertCreateCertificateContext( int dwCertEncodingType, IntPtr pbCertEncoded, int cbCertEncoded ); [DllImport("Crypt32.dll", SetLastError = true)] public static extern Boolean CertFreeCertificateContext( IntPtr pCertContext ); [DllImport("Crypt32.dll", SetLastError = true)] public static extern IntPtr CertOpenStore( int lpszStoreProvider, int dwMsgAndCertEncodingType, IntPtr hCryptProv, int dwFlags, IntPtr pvPara ); [DllImport("Crypt32.dll", SetLastError = true)] public static extern IntPtr CertGetSubjectCertificateFromStore( IntPtr hCertStore, int dwCertEncodingType, IntPtr pCertId ); [DllImport("Crypt32.dll", SetLastError = true)] public static extern IntPtr CertCloseStore( IntPtr hCertStore, int dwFlags ); #endregion } }

    Read the article

  • Is NAN suitable for communicating that an invalid parameter was involved in a calculation?

    - by Arman
    I am currently working on a numerical processing system that will be deployed in a performance-critical environment. It takes inputs in the form of numerical arrays (these use the eigen library, but for the purpose of this question that's perhaps immaterial), and performs some range of numerical computations (matrix products, concatenations, etc.) to produce outputs. All arrays are allocated statically and their sizes are known at compile time. However, some of the inputs may be invalid. In these exceptional cases, we still want the code to be computed and we still want outputs not "polluted" by invalid values to be used. To give an example, let's take the following trivial example (this is pseudo-code): Matrix a = {1, 2, NAN, 4}; // this is the "input" matrix Scalar b = 2; Matrix output = b * a; // this results in {2, 4, NAN, 8} The idea here is that 2, 4 and 8 are usable values, but the NAN should signal to the receipient of the data that that entry was involved in an operation that involved an invalid value, and should be discarded (this will be detected via a std::isfinite(value) check before the value is used). Is this a sound way of communicating and propagating unusable values, given that performance is critical and heap allocation is not an option (and neither are other resource-consuming constructs such as boost::optional or pointers)? Are there better ways of doing this? At this point I'm quite happy with the current setup but I was hoping to get some fresh ideas or productive criticism of the current implementation.

    Read the article

  • Invalid URI: The Uri scheme is too long

    - by phenevo
    Hi, I have XML: Which is result of this part of query: SELECT Countries.FileSystemName as country ,Regions.DefaultName as region ,Provinces.DefaultName as province,cities.defaultname as city,cities.code as cityCode, IndividualFlagsWithForObjects.value as Status I have xslt: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" encoding="iso-8859-1"/> <xsl:param name="delim" select="string(',')" /> <xsl:param name="quote" select="string('&quot;')" /> <xsl:param name="break" select="string('&#xD;')" /> <xsl:template match="/"> <xsl:apply-templates select="results/countries" /> </xsl:template> <xsl:template match="countries"> <xsl:apply-templates /> <xsl:if test="following-sibling::*"> <xsl:value-of select="$break" /> </xsl:if> </xsl:template> <xsl:template match="*"> <!-- remove normalize-space() if you want keep white-space at it is --> <xsl:value-of select="concat($quote, normalize-space(.), $quote)" /> <xsl:if test="following-sibling::*"> <xsl:value-of select="$delim" /> </xsl:if> </xsl:template> <xsl:template match="text()" /> </xsl:stylesheet> And is part of code XmlReader reader = cmd.ExecuteXmlReader(); doc.LoadXml("<results></results>"); XmlNode newNode = doc.ReadNode(reader); while (newNode != null) { doc.DocumentElement.AppendChild(newNode); newNode = doc.ReadNode(reader); } doc.Save(@"c:\listOfCities.xml"); XslCompiledTransform XSLT = new XslCompiledTransform(); XsltSettings settings = new XsltSettings(); settings.EnableScript = true; XSLT.Load(@"c:\xsltfile1.xslt", settings, new XmlUrlResolver()); XSLT.Transform(doc.OuterXml,@"c:\myCities.csv"); <-here I get error Why I get error. Is seems to be good .

    Read the article

  • Linq to sql Invalid column name

    - by Ivo
    I am using VS 2010 and Linq-to-sql I have deleted a couple of columns from my table, whatever I try I keep getting and "invalide column name" error with the old/deleted column when I try to insert a record. What tried: remove table,save, and drag it back on create new dblm with an other name created new project and create new dbml there Also the name of the deleted column does not exist in the generated code of the dbml anymore, but still I get an exception saying that column does not exists. Anyone got a suggestion how to solve this problem?

    Read the article

  • android include tag - invalid layout refernce

    - by Dalibor Frivaldsky
    Hello, I'm having a problem including a different layout through the include tag in the android layout xml file. When specifing the layout reference ( @layout/... ), i'm getting a InflateException in the Eclipse ADT with the following error: InflateException: You must specifiy a valid layout reference. The layout ID @layout/func_edit_simple_calculator_toolbox is not valid. the reference should be valid, as I've selected it from the the list of my other layouts and didnt type it in. I'm using android sdk v2.1 these are the layout files func_edit_simple_calculator_toolbox.xml <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="wrap_content"> <TableRow android:id="@+id/TableRow01" android:layout_width="wrap_content"android:layout_height="wrap_content"> <Button android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="1"></Button> <Button android:id="@+id/Button02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="2"></Button> <Button android:id="@+id/Button03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="3"></Button> <Button android:id="@+id/Button04" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="+"></Button> </TableRow> <TableRow android:id="@+id/TableRow02" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/Button05" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="4"></Button> <Button android:id="@+id/Button06" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="5"></Button> <Button android:id="@+id/Button07" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="6"></Button> <Button android:id="@+id/Button08" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="-"></Button> </TableRow> </TableLayout> function_editor_layout.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <com.calculoid.FunctionView android:id="@+id/function_view" android:layout_width="fill_parent" android:layout_height="fill_parent"/> <include android:id="@+id/include01" android:layout_width="wrap_content" android:layout_height="wrap_content" layout="@layout/func_edit_simple_calculator_toolbox"></include> </LinearLayout> Does any one know what could be the problem? thanks in advance

    Read the article

  • iPhone: Application Install Fails With "Invalid Signer" Error

    - by Scot
    The iPhone is attached to a Mac runnning the latest iTunes version and I am 100% sure that her UDID is in the provisioning file. Her iPhone has not been jailbroken and we even restored it to factory settings. I am having trouble installing our development build on this one iPhone. The error is: the application "[Application Name]" was not installed on the iPhone "iPhone" because the signer is not valid I am 100% sure that the UDID is accurately entered in the provisioning file and that they correctly copied the right provision file/build combo. This same combo has been successfully installed on over a dozen iphones. We have been able to install this on some devices with no problems. Edit: From comments to an answer: We can install it on 100 iphone with our account. We have about 40 iphones in this provisioning profile and it works on 38 of them.

    Read the article

  • nant: invalid element nunit2. Unknown task or datatype

    - by stacker
    How to solve this problem? I have this ProjectName.UnitTests.config file, and I did exactly what the documentation said: http://nant.sourceforge.net/release/latest/help/tasks/nunit2.html <?xml version="1.0" encoding="utf-8" ?> <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="nunit.framework" publicKeyToken="96d09a1eb7f44a77" culture="Neutral" /> <bindingRedirect oldVersion="2.0.6.0" newVersion="2.2.8.0" /> <bindingRedirect oldVersion="2.1.4.0" newVersion="2.2.8.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>

    Read the article

  • How to parse invalid HTML with Perl?

    - by bodacydo
    I maintain a database of articles with HTML formatting. Unfortunately the editors who wrote articles didn't know proper HTML, so they often have written stuff like: <div class="highlight"><html><head></head><body><p>Note that ...</p></html></div> I tried using HTML::TreeBuilder to parse this HTML but after parsing it and dumping the resulting tree, all the elements between <div class="highlight">...</div> are gone. I'm left with just <div class="highlight"></div>. The editors often have also done things like: <div class="article"><style>@font-face { font-family: "Cambria"; }</style>Article starts here</div> Parsing this with HTML::TreeBuilder results in empty <div class="article"></div> again. Any ideas how to approach this broken HTML and actually make sense out of it?

    Read the article

  • Failed Castle ActiveRecord TransactionScope causes future queries to be invalid

    - by mbp
    I am trying to solve an issue when using a Castle ActiveRecord TransactionScope which is rolled back. After the rollback, I am unable to query the Dog table. The "Dog.FindFirst()" line fails with "Could not perform SlicedFindAll for Dog", because it cannot insert dogMissingName. using (new SessionScope()) { try { var trans = new TransactionScope(TransactionMode.New, OnDispose.Commit); try { var dog = new Dog { Name = "Snowy" }; dog.Save(); var dogMissingName = new Dog(); dogMissingName.Save(); } catch (Exception) { trans.VoteRollBack(); throw; } finally { trans.Dispose(); } } catch (Exception ex) { var randomDog = Dog.FindFirst() Console.WriteLine("Random dog : " + randomDog.Name); } } Stacktrace is as follows: Castle.ActiveRecord.Framework.ActiveRecordException: Could not perform SlicedFindAll for Dog ---> NHibernate.Exceptions.GenericADOException: could not insert: [Mvno.Dal.Dog#219e86fa-1081-490a-92d1-9d480171fcfd][SQL: INSERT INTO Dog (Name, Id) VALUES (?, ?)] ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Name', table 'Dog'; column does not allow nulls. INSERT fails. The statement has been terminated. ved System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) ved System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) ved System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) ved System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) ved System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) ved System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) ved System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) ved System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) ved System.Data.SqlClient.SqlCommand.ExecuteNonQuery() ved NHibernate.AdoNet.AbstractBatcher.ExecuteNonQuery(IDbCommand cmd) ved NHibernate.AdoNet.NonBatchingBatcher.AddToBatch(IExpectation expectation) ved NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session) --- End of inner exception stack trace --- ved NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session) ved NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Object obj, ISessionImplementor session) ved NHibernate.Action.EntityInsertAction.Execute() ved NHibernate.Engine.ActionQueue.Execute(IExecutable executable) ved NHibernate.Engine.ActionQueue.ExecuteActions(IList list) ved NHibernate.Engine.ActionQueue.ExecuteActions() ved NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session) ved NHibernate.Event.Default.DefaultAutoFlushEventListener.OnAutoFlush(AutoFlushEvent event) ved NHibernate.Impl.SessionImpl.AutoFlushIfRequired(ISet`1 querySpaces) ved NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) ved NHibernate.Impl.CriteriaImpl.List(IList results) ved NHibernate.Impl.CriteriaImpl.List() ved Castle.ActiveRecord.ActiveRecordBase.SlicedFindAll(Type targetType, Int32 firstResult, Int32 maxResults, Order[] orders, ICriterion[] criteria) --- End of inner exception stack trace --- ved Castle.ActiveRecord.ActiveRecordBase.SlicedFindAll(Type targetType, Int32 firstResult, Int32 maxResults, Order[] orders, ICriterion[] criteria) ved Castle.ActiveRecord.ActiveRecordBase.FindFirst(Type targetType, Order[] orders, ICriterion[] criteria) ved Castle.ActiveRecord.ActiveRecordBase.FindFirst(Type targetType, ICriterion[] criteria) ved Castle.ActiveRecord.ActiveRecordBase`1.FindFirst(ICriterion[] criteria)

    Read the article

  • iPhone StoreKit - invalid product id's

    - by Achim
    I'm trying to test the in App purchase within the sandbox environment. In order to test the code I a) created a In App Purchase Test User account under 'Manage Users' in iTunes Connect b) created some in app purchase products under 'Manage Your In App Purchases'. I used numeric values and alpha-numeric values for the Product ID's. c) Loaded the app onto the iPhone, went to Settings-Store and logged out of the regular store and into the under a) created test account d) set a breakpoint in the (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response callback All the submitted Product ID's are in the response.invalidProductIdentifiers category. When submitting the request I use either the Product ID's used under b) directly or I tried to prefix them with the Bundle ID: NSString *id2 = @"com.super.duper.8"; NSSet *productList = [NSSet setWithObjects:id2, @"8", nil]; SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:productList]; Am I missing something obvious? Any help is appreciated. Achim

    Read the article

  • Generated signed X.509 client certificate is invalid (no certificate chain to its CA)

    - by Genady
    I use Bouncy Castle for generation of X.509 client certificates and sing them using a known CA. First I read the CA certificate from the certificate store, generate the client certificate, sign it using the CA. Validation of the certificate is failed doe to the following issue A certificate chain could not be built to a trusted root authority. As I understand this is due to the certificate not being related to the CA. Here is a code sample: public static X509Certificate2 GenerateCertificate(X509Certificate2 caCert, string certSubjectName) { // Generate Certificate var cerKp = kpgen.GenerateKeyPair(); var certName = new X509Name(true,certSubjectName); // subjectName = user var serialNo = BigInteger.ProbablePrime(120, new Random()); X509V3CertificateGenerator gen2 = new X509V3CertificateGenerator(); gen2.SetSerialNumber(serialNo); gen2.SetSubjectDN(certName); gen2.SetIssuerDN(new X509Name(true,caCert.Subject)); gen2.SetNotAfter(DateTime.Now.AddDays(100)); gen2.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); gen2.SetSignatureAlgorithm("SHA1WithRSA"); gen2.SetPublicKey(cerKp.Public); AsymmetricCipherKeyPair akp = DotNetUtilities.GetKeyPair(caCert.PrivateKey); Org.BouncyCastle.X509.X509Certificate newCert = gen2.Generate(caKp.Private); // used for getting a private key X509Certificate2 userCert = ConvertToWindows(newCert,cerKp); if (caCert22.Verify()) // works well for CA { if (userCert.Verify()) // fails for client certificate { return userCert; } } return null; } private static X509Certificate2 ConvertToWindows(Org.BouncyCastle.X509.X509Certificate newCert, AsymmetricCipherKeyPair kp) { string tempStorePwd = "abcd1234"; var tempStoreFile = new FileInfo(Path.GetTempFileName()); try { // store key { var newStore = new Pkcs12Store(); var certEntry = new X509CertificateEntry(newCert); newStore.SetCertificateEntry( newCert.SubjectDN.ToString(), certEntry ); newStore.SetKeyEntry( newCert.SubjectDN.ToString(), new AsymmetricKeyEntry(kp.Private), new[] { certEntry } ); using (var s = tempStoreFile.Create()) { newStore.Save( s, tempStorePwd.ToCharArray(), new SecureRandom(new CryptoApiRandomGenerator()) ); } } // reload key return new X509Certificate2(tempStoreFile.FullName, tempStorePwd); } finally { tempStoreFile.Delete(); } }

    Read the article

  • OneWay binding throws "TwoWay binding is invalid on Read only property"

    - by Binary Worrier
    This binding <tk:DataGridTextColumn Binding="{Binding Path=Id, Mode=OneWay}" Header="Sale No." Width="1*" /> Gives this error A TwoWay or OneWayToSource binding cannot work on the read-only property 'Id' of type . . . The "Id" property is indeed readonly, I thought though that Mode=OneWay would be sufficient. I'm tired and I know I'm missing something obvious so I'll apologies now for asking a really dumb question. Thanks BW

    Read the article

  • Invalid message signature when running OpenId Provider on Cluster

    - by Garth
    Introduction We have an OpenID Provider which we created using the DotNetOpenAuth component. Everything works great when we run the provider on a single node, but when we move the provider to a load balanced cluster where multiple servers are handling requests for each session we get issue with the message signing as the DotNetOpenAuth component seems to be using something unique from each cluster node to create the signature. Exception DotNetOpenAuth.Messaging.Bindings.InvalidSignatureException: Message signature was incorrect. at DotNetOpenAuth.OpenId.ChannelElements.SigningBindingElement.ProcessIncomingMessage(IProtocolMessage message) in c:\BuildAgent\work\7ab20c0d948e028f\src\DotNetOpenAuth\OpenId\ChannelElements\SigningBindingElement.cs:line 139 at DotNetOpenAuth.Messaging.Channel.ProcessIncomingMessage(IProtocolMessage message) in c:\BuildAgent\work\7ab20c0d948e028f\src\DotNetOpenAuth\Messaging\Channel.cs:line 940 at DotNetOpenAuth.OpenId.ChannelElements.OpenIdChannel.ProcessIncomingMessage(IProtocolMessage message) in c:\BuildAgent\work\7ab20c0d948e028f\src\DotNetOpenAuth\OpenId\ChannelElements\OpenIdChannel.cs:line 172 at DotNetOpenAuth.Messaging.Channel.ReadFromRequest(HttpRequestInfo httpRequest) in c:\BuildAgent\work\7ab20c0d948e028f\src\DotNetOpenAuth\Messaging\Channel.cs:line 378 at DotNetOpenAuth.OpenId.RelyingParty.OpenIdRelyingParty.GetResponse(HttpRequestInfo httpRequestInfo) in c:\BuildAgent\work\7ab20c0d948e028f\src\DotNetOpenAuth\OpenId\RelyingParty\OpenIdRelyingParty.cs:line 493 Setup We have the machine config setup to use the same machine key on all cluster nodes and we have setup an out of process session with SQL Server. Question How do we configure the key used by DotNetOpenAuth to sign its messages so that the client will trust responses from all servers in the cluster during the same session?

    Read the article

  • Powershell: Get-Process Returns "Invalid" VM Size

    - by dewald
    I'm running PowerShell 2.0 on Windows XP SP3 and I execute: PS> ps firefox And it returns: Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 859 44 340972 351580 684 9,088.22 7744 firefox However, Windows Task Manager shows the following stats for firefox.exe: Mem Usage: 354,720 K VM Size: 347,322 K Why is the VM output from PowerShell 300 MB more than that output from Windows Task Manager?

    Read the article

  • storekit In app purchase invalid product identifiers

    - by Sridhar
    Hello, I am getting zero product identifiers from SKProductsRequest I did the following steps a) created a In App Purchase Test User account under 'Manage Users' in iTunes Connect b) created some in app purchase products under 'Manage Your In App Purchases'. c) Loaded the app onto the iPhone, went to Settings-Store and logged out of the regular store d) set a breakpoint in the (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response callback All the submitted Product ID's are in the response.invalidProductIdentifiers category. When submitting the request I use either the Product ID's used under b) directly or I tried to prefix them with the Bundle ID: Thanks In Adavance Raghu,

    Read the article

  • Invalid Cast Exception ASP.NET C#

    - by Shadow Scorpion
    I have a problem in this code: public static T[] GetExtras <T>(Type[] Types) { List<T> Res = new List<T>(); foreach (object Current in GetExtras(typeof(T), Types)) { Res.Add((T)Current);//this is the error } return Res.ToArray(); } public static object[] GetExtras(Type ExtraType, Type[] Types) { lock (ExtraType) { if (!ExtraType.IsInterface) return new object[] { }; List<object> Res = new List<object>(); bool found = false; found = (ExtraType == typeof(IExtra)); foreach (Type CurInterFace in ExtraType.GetInterfaces()) { if (found = (CurInterFace == typeof(IExtra))) break; } if (!found) return new object[] { }; foreach (Type CurType in Types) { found = false; if (!CurType.IsClass) continue; foreach (Type CurInterface in CurType.GetInterfaces()) { try { if (found = (CurInterface.FullName == ExtraType.FullName)) break; } catch { } } try { if (found) Res.Add(Activator.CreateInstance(CurType)); } catch { } } return Res.ToArray(); } } When I'm using this code in windows application it works! But I cant use it on ASP page. Why?

    Read the article

  • Ubuntu 10.04 (Lucid) OpenLDAP invalid credentials issue

    - by gmuller
    This won't be a question, but a solution to an infuriating problem on Ubuntu 10.04. If you tried to deploy an LDAP server using this distro following the tutorials below, you'll be on serious trouble. Tutorials: https://help.ubuntu.com/9.10/serverguide/C/openldap-server.html https://help.ubuntu.com/9.10/serverguide/C/samba-ldap.html The error first appear, on the line: "ldapsearch -xLLL -b cn=config -D cn=admin,cn=config -W olcDatabase=hdb olcAccess" It simply won't allow admin to access the "cn=config", thus you won't be able to deploy the LDAP server correctly. After almost a week searching for a solution, I've found this page: https://bugs.launchpad.net/ubuntu-docs/+bug/333733 On comment #5, the solution is presented. Quoting the author: when you get to the setting up ACL part you all of a sudden need to use a cn=admin,cn=config, that doesn't exist creating a config.ldif with dn: olcDatabase={0}config,cn=config changetype: modify add: olcRootDN olcRootDN: cn=admin,cn=config dn: olcDatabase={0}config,cn=config changetype: modify add: olcRootPW olcRootPW: secret dn: olcDatabase={0}config,cn=config changetype: modify delete: olcAccess and adding it with ldapadd -Y EXTERNAL -H ldapi:/// -f config.ldif It's unacceptable that a Linux distribution, popular like Ubuntu, have such ridiculous bug. Hope it helps everyone!

    Read the article

  • Maven problem with invalid jar file which is actually html

    - by fei
    i'm running into a problem in my maven build recently, that it downloads a jar file for the javamail-1.4.jar or something, but it turns out the file is not a real jar file, it's actually a html with a link to where to get the correct jar. it seems to be the repo has changed for that. but in my maven setting everything is supposely to go to our internal repo, i don't know how did that happen. but anyways, more importantly, how do i fix this problem so that it will download the correct jar file on a fresh install? thanks!

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >