WCF 400 Bad request

Данная проблема начала возникать на моем сервисе. После гугления интернета наткнулся на то что она может проявляться из-за неверного представления адреса сервиса или из-за больших объемов данных. Есть наверняка и множество других причин, но в моем случае это был большой объем данных получаемый на входе сервисом.

Данную проблему можно решить двумя способами:
1 Посредством исправления web.config . Курсивом и жирным обозначено что нужно поправить. Веб конфиг необходимо править если вы развертываете сервис на своем IIS

<system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfService2.Service1Behavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />          
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="WcfService2.Service1Behavior"
        name="WcfService2.Service1">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="b1" contract="WcfService2.IService1">
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="b1" maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="2147483647"
                        maxStringContentLength="2147483647"
                        maxArrayLength="2147483647"
                        maxBytesPerRead="2147483647"
                        maxNameTableCharCount="2147483647" />

        </binding>
      </basicHttpBinding>
    </bindings>
  </system.serviceModel>

2 Второй способ актуален для тех кто развертывает сервис через new ServiceHost() . Почитать о нём можно тут . В данном случае мы меняем readerQuotas программно.

using (ServiceHost host = new ServiceHost(typeof(WCF_Lic_SA.ServiceLicSA), new Uri("http://localhost:8202/MyService")))
            {
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();

                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);
                host.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;
                host.OpenTimeout = TimeSpan.FromSeconds(10);

                BasicHttpBinding b = new BasicHttpBinding();

                System.Xml.XmlDictionaryReaderQuotas myReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas();
                myReaderQuotas.MaxArrayLength = 2147483647;
                myReaderQuotas.MaxBytesPerRead = 2147483647;
                myReaderQuotas.MaxDepth = 2147483647;
                myReaderQuotas.MaxNameTableCharCount = 2147483647;
                myReaderQuotas.MaxStringContentLength = 2147483647;
                b.ReaderQuotas = myReaderQuotas;
                b.MaxBufferPoolSize = 2147483647;
                b.MaxBufferSize = 2147483647;
                b.MaxReceivedMessageSize = 2147483647;

                host.AddServiceEndpoint(typeof(WCF_Lic_SA.IServiceLicSA), b, "");

                host.Open();
            }

Не удалось обновить зависимости проекта. Зависимости объекта <имя dll> не удается установить.


Вот нашел в блогах решение может кому поможет http://sharpgreat.blogspot.ru/2012/09/mydll.html

Мою ситуацию решило удаление "основные выходные файлы" из обозревателя решений VS.
После я заново добавил "основные выходные файлы" и всё заработало.

Потом ещё возникала проблема с обновлением каких то "действий" тоже проекте устновщика, тоже их решал удалением и обновлением новых ссылок.

Вообще вот много сообщений об ошибках из данной ситуации и пути их решения http://msdn.microsoft.com/ru-ru/library/yhteff89(v=vs.90).aspx

C# MSSQL Simple example Read data


using System;
using System.Data;
using System.Data.SqlClient;


class Program
{
    static void Main()
    {
        string str = "Data Source=(local);Initial Catalog=Northwind;"
            + "Integrated Security=SSPI";
        ReadOrderData(str);
    }

    private static void ReadOrderData(string connectionString)
    {
        string queryString =
            "SELECT OrderID, CustomerID FROM dbo.Orders;";

        using (SqlConnection connection =
                   new SqlConnection(connectionString))
        {
            SqlCommand command =
                new SqlCommand(queryString, connection);
            connection.Open();

            SqlDataReader reader = command.ExecuteReader();

            // Call Read before accessing data. 
            while (reader.Read())
            {
                ReadSingleRow((IDataRecord)reader);
            }

            // Call Close when done reading.
            reader.Close();
        }
    }

    private static void ReadSingleRow(IDataRecord record)
    {
        Console.WriteLine(String.Format("{0}, {1}", record[0], record[1]));
    }

}

SQL Compact connection string "Data Source=C:\userDB.sdf;Password=password;Persist Security Info=True"

In thos case dont forget to use CE components, for example System.Data.SqlServerCe.SqlCeConnection

101 Пример использования LINQ

Нашел ссылку, очень много полезных примеров применения LINQ http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

с# Serialization to file or string / с# Сериализация в файл или в строку + Десериализация

static void SerializeToFile(object o)
{
  XmlSerializer serializer = new XmlSerializer(o.GetType());
  using (Stream writer = new FileStream("output.xml", FileMode.Create))
  {
    serializer.Serialize(writer, o);
  }
}

public static string SerializeToString(object obj)
        {
            XmlSerializer serializer = new XmlSerializer(obj.GetType());

            using (StringWriter writer = new StringWriter())
            {
                serializer.Serialize(writer, obj);

                return writer.ToString();
            }
        }
public static object DeserializeFromFile(object obj,string path)
{
  XmlSerializer serializer = new XmlSerializer(obj.GetType());
 
  using (XmlReader reader = XmlReader.Create(path))
  {
    object o = serializer.Deserialize(reader);
  }
}

//From string

var serializer = new XmlSerializer(typeof(Car));
using (var reader = new StringReader(xml))
{
    var car = (Car)serializer.Deserialize(reader);
}

Изменить строку подключения в app.conig / How to change connection string in app.config

static void AddConnectionStringMyDB()
        {
            System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);
            ConnectionStringsSection csSection =
              config.ConnectionStrings;
            ConnectionStringSettings connection = new ConnectionStringSettings();
            connection.Name = "Rozn_Client.Properties.Settings.userDBConnectionString";
            connection.ProviderName = "Microsoft.SqlServerCe.Client.4.0";
            connection.ConnectionString = "Data Source=|DataDirectory|\\myDB.sdf;Password=mypassword;Persist Security Info=True";
            csSection.ConnectionStrings.Add(connection);
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("connectionStrings");
        }

C# Get the version of your solution in Visual Studio

string s1 = Application.ProductVersion; //Only product version
string s2 = System.Reflection.Assembly.GetExecutingAssembly().FullName; // Returns Project1, Version=1.0.2281.26155, Culture=neutral, PubliKeyToken=null

c# получить из сертификата открытый и закрытый ключ / Get from X509 certificate private and public keys

X509Certificate2 cert = new X509Certificate2("cert.pfx");
//(RSACryptoServiceProvider)cert.PrivateKey
//(RSACryptoServiceProvider)cert.PublicKey.Key

c# проверяем подпись сертификата x509 у файла / c# Verify x509 certificate signature

public static bool CertificateSignVerify(string signFilePath, byte[] data, RSACryptoServiceProvider rsaKey)
        {
            byte[] signature = File.ReadAllBytes(signFilePath);
            return rsaKey.VerifyData(data, new SHA1CryptoServiceProvider(), signature);
        }

c# How to encrypt file using x509 certificate

public static void EncryptFile(string encrDumpFilePath, string dumpFilePath, RSACryptoServiceProvider rsaKey)
        {
            using (AesManaged aesManaged = new AesManaged())
            {
                aesManaged.KeySize = 256;
                aesManaged.BlockSize = 128;
                aesManaged.Mode = CipherMode.CBC;
                using (ICryptoTransform transform = aesManaged.CreateEncryptor())
                {
                    RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(rsaKey);
                    byte[] keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType());
                    byte[] LenK = new byte[4];
                    byte[] LenIV = new byte[4];
                    int lKey = keyEncrypted.Length;
                    LenK = BitConverter.GetBytes(lKey);
                    int lIV = aesManaged.IV.Length;
                    LenIV = BitConverter.GetBytes(lIV);
                    int startFileName = dumpFilePath.LastIndexOf("\\") + 1;

                    string outFile = encrDumpFilePath;
                    Directory.CreateDirectory(Path.GetDirectoryName(encrDumpFilePath));
                    using (FileStream outFs = new FileStream(outFile, FileMode.Create))
                    {
                        outFs.Write(LenK, 0, 4);
                        outFs.Write(LenIV, 0, 4);
                        outFs.Write(keyEncrypted, 0, lKey);
                        outFs.Write(aesManaged.IV, 0, lIV);
                        using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                        {
                            int count = 0;
                            int offset = 0;
                            int blockSizeBytes = aesManaged.BlockSize / 8;
                            byte[] data = new byte[blockSizeBytes];
                            int bytesRead = 0;

                            using (FileStream inFs = new FileStream(dumpFilePath, FileMode.Open))
                            {
                                do
                                {
                                    count = inFs.Read(data, 0, blockSizeBytes);
                                    offset += count;
                                    outStreamEncrypted.Write(data, 0, count);
                                    bytesRead += blockSizeBytes;
                                }
                                while (count > 0);
                                inFs.Close();
                            }
                            outStreamEncrypted.FlushFinalBlock();
                            outStreamEncrypted.Close();
                        }
                        outFs.Close();
                    }
                }
            }
        }

c# Расшифровываем файл, зашифрованный ключом из сертификата x509 / x509 Certificate Decrypt file

public static MemoryStream DecryptFile(string dumpFilePath, RSACryptoServiceProvider rsaKey)
        {
            MemoryStream outFs = new MemoryStream();
            using (AesManaged aesManaged = new AesManaged())
            {
                aesManaged.KeySize = 256;
                aesManaged.BlockSize = 128;
                aesManaged.Mode = CipherMode.CBC;
                byte[] LenK = new byte[4];
                byte[] LenIV = new byte[4];
                using (FileStream inFs = new FileStream(dumpFilePath, FileMode.Open))
                {
                    inFs.Seek(0, SeekOrigin.Begin);
                    inFs.Seek(0, SeekOrigin.Begin);
                    inFs.Read(LenK, 0, 3);
                    inFs.Seek(4, SeekOrigin.Begin);
                    inFs.Read(LenIV, 0, 3);
                    int lenK = BitConverter.ToInt32(LenK, 0);
                    int lenIV = BitConverter.ToInt32(LenIV, 0);
                    int startC = lenK + lenIV + 8;
                    int lenC = (int)inFs.Length - startC;
                    byte[] KeyEncrypted = new byte[lenK];
                    byte[] IV = new byte[lenIV];
                    inFs.Seek(8, SeekOrigin.Begin);
                    inFs.Read(KeyEncrypted, 0, lenK);
                    inFs.Seek(8 + lenK, SeekOrigin.Begin);
                    inFs.Read(IV, 0, lenIV);
                    byte[] KeyDecrypted = rsaKey.Decrypt(KeyEncrypted, false);
                    using (ICryptoTransform transform = aesManaged.CreateDecryptor(KeyDecrypted, IV))
                    {
                        int count = 0;
                        int offset = 0;
                        int blockSizeBytes = aesManaged.BlockSize / 8;
                        byte[] data = new byte[blockSizeBytes];
                        inFs.Seek(startC, SeekOrigin.Begin);
                        using (CryptoStream outStreamDecrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                        {
                            do
                            {
                                count = inFs.Read(data, 0, blockSizeBytes);
                                offset += count;
                                outStreamDecrypted.Write(data, 0, count);
                            }
                            while (count > 0);

                            outStreamDecrypted.FlushFinalBlock();
                        }
                    }

                }

            }
            return outFs;

        }

c# возвращаем сертификат из файла / C# get certificate from .crt .pfx file

public static X509Certificate2 GetCertificateFromFile(string certPath)
        {
            return new X509Certificate2(certPath);
        }

c# Возвращаем сертификат из хранилища Windows сертификатов / c# get certificate from windows store

public static X509Certificate2 GetCertificateFromStore(string certName)
        {
            X509Store store = new X509Store(StoreLocation.CurrentUser);
            try
            {
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certCollection = store.Certificates;
                X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
                X509Certificate2 o = currentCerts[0];
                X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectName, certName, false);
                if (signingCert.Count == 0)
                    return null;
                return signingCert[0];
            }
            finally
            {
                store.Close();
            }

        }

c# подписываем файл сертификатом,полученную сигнатуру записываем в файл

public static bool CertificateSign(string signFilePath, string dumpFilePath, RSACryptoServiceProvider rsaKey)
        {
            byte[] data = null;
            using (System.IO.FileStream _FileStream = new System.IO.FileStream(dumpFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            using (System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream))
            {

                long _TotalBytes = new System.IO.FileInfo(dumpFilePath).Length;
                data = _BinaryReader.ReadBytes((Int32)_TotalBytes);
            }

            byte[] signature = rsaKey.SignData(data, new SHA1CryptoServiceProvider());
            File.WriteAllBytes(signFilePath, signature);
            return false;
        }

c# получить хэш файла / c# get hash from file

public static string GetMD5HashFromFile(string fileName)
        {
            FileStream file = new FileStream(fileName, FileMode.Open);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(file);
            file.Close();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }

c# читаем последнюю строку и удаляем её / Get last line from file and delete it

private static string ReadDeleteHashFromFile(string MyFilePath)
{
            string lastline = "";
            using (StreamReader reader = new StreamReader(dumpFilePath))
            {
                using (StreamWriter writer = new StreamWriter("myfile.tmp"))
                {
                    string line = reader.ReadLine();
                    
                    while (!reader.EndOfStream)
                    {
                        writer.Write(line);
                        line = reader.ReadLine();
                        if (!reader.EndOfStream)
                            writer.Write(writer.NewLine);
                    }
                    lastline = line;
                }
            }
            File.Delete(MyFilePath);
            File.Move("myfile.tmp", MyFilePath);
            File.Delete("myfile.tmp");
            return lastline;
}

c# add a line to the end of a file

using (StreamWriter sw = new StreamWriter(dumpFilePath, true, Encoding.ASCII))
            {
                string s="My new line";
                sw.WriteLine();
                sw.Write(s);
                sw.Close();
            }

c# фильтр datagridview


string namestr = "MyColumnName";
BindingSource.Filter = " name LIKE'" + namestr + "%'";

с# работа с API / c# work with API


Для использования в программе API-функций надо, во-первых, добавить постранство имен System.Runtime.InteropServices, во-вторых, добавить заголовок нужной API-функции и в-третьих, вызвать ее в нужном месте.

Код:

using System;
...
//Добавление пространства имен
using System.Runtime.InteropServices;
...
        //Добавление заголовка
[DllImport("user32.dll", EntryPoint="MessageBox")]
        public static extern int MessageBox(int hWnd,
        String strMessage, String strCaption, uint uiType);
...
private void button1_Click(object sender, System.EventArgs e)
        {
            //Вызов API-функции
            MessageBox(0, "Hello!", "Caption", 0);
        }
    ...

В указанном примере при нажатии на кнопку выскочит MessageBox (путем вызова соответствующей API-функции).

с# application settings MSDN


http://msdn.microsoft.com/ru-ru/library/wabtadw6.aspx пошаговое описание

http://msdn.microsoft.com/ru-ru/library/a65txexh.aspx сам мини кусок кода

Properties.Settings.Default.FirstUserSetting = "abc";
Properties.Settings.Default.Save();

C# connect to dbf

using System.Data.OleDb;

...

            OleDbConnection _connection = new OleDbConnection();
            StringBuilder ConnectionString = new StringBuilder("");
            ConnectionString.Append(@"Provider=Microsoft.Jet.OLEDB.4.0;");
            ConnectionString.Append(@"Extended Properties=Paradox 5.x;");
            ConnectionString.Append(@"Data Source=D:\dbf;");
            _connection.ConnectionString = ConnectionString.ToString();
            try { _connection.Open(); }
            catch (Exception _e) { MessageBox.Show("Error openning database! " + _e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
            OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM kadr.db;", _connection);
            DataSet dsRetrievedData = new DataSet();
            da.Fill(dsRetrievedData);
            this.dataGridView1.DataSource = dsRetrievedData;
            this.dataGridView1.DataMember = dsRetrievedData.Tables[0].TableName;

С# запрос к базе / c# request to base

SqlCommand cmd = new SqlCommand("update table set bestOfTheBestField=@par where Na uslovie fantazii ne hvatilo");
cmd.Parameters.Add("@par", SqlDbType.Int).Value = (int)this.textBox.Text.Trim();
return cmd.ExecuteNonQuery();

дизасемблер для приложений .NET / Disassembler for .NET Applications


Приведенная ниже команда выводит метаданные и дизассемблированный код PE-файла MyHello.exe в стандартном графическом интерфейсе пользователя программы Ildasm.exe.
Копировать
ildasm myHello.exe
Копировать
ildasm myHello.exe

Приведенная ниже команда дизассемблирует файл MyFile.exe и сохраняет выходной текст для ассемблера MSIL в файле MyFile.il.
Копировать
ildasm MyFile.exe /output:MyFile.il
Копировать
ildasm MyFile.exe /output:MyFile.il

Приведенная ниже команда дизассемблирует файл MyFile.exe и выводит выходной текст для ассемблера MSIL на консоль.
Копировать
ildasm MyFile.exe /text
Копировать
ildasm MyFile.exe /text

Если файл MyApp.exe содержит внедренные управляемые и неуправляемые ресурсы, в результате выполнения следующей команды будет создано четыре файла: MyApp.il, MyApp.res, Icons.resources, и Message.resources.
Копировать
ildasm MyApp.exe /output:MyApp.il
Копировать
ildasm MyApp.exe /output:MyApp.il

Приведенная ниже команда дизассемблирует метод MyMethod класса MyClass в файле MyFile.exe и выводит результат в окно консоли.
Копировать
ildasm /item:MyClass::MyMethod MyFile.exe /text
Копировать
ildasm /item:MyClass::MyMethod MyFile.exe /text

В предыдущем примере допустимо наличие нескольких методов с именем MyMethod и различными подписями. Приведенная ниже команда дизассемблирует метод экземпляра MyMethod с типом возвращаемого значения void и типами параметров int32 и string.
Копировать
ildasm /item:"MyClass::MyMethod(instance void(int32,string)" MyFile.exe /text

c# универсальные шаблоны

// Declare the generic class.
public class GenericList<T>
{
    void Add(T input) { }
}
class TestGenericList
{
    private class ExampleClass { }
    static void Main()
    {
        // Declare a list of type int.
        GenericList<int> list1 = new GenericList<int>();

        // Declare a list of type string.
        GenericList<string> list2 = new GenericList<string>();

        // Declare a list of type ExampleClass.
        GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
    }
}

c# Delete and copy files with replacing

string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";

try
{
    string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
    string[] txtList = Directory.GetFiles(sourceDir, "*.txt");

    // Copy picture files.
    foreach (string f in picList)
    {
        // Remove path from the file name.
        string fName = f.Substring(sourceDir.Length + 1);

        // Use the Path.Combine method to safely append the file name to the path.
        // Will overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
    }

    // Copy text files.
    foreach (string f in txtList)
    {

        // Remove path from the file name.
        string fName = f.Substring(sourceDir.Length + 1);

        try
        {
            // Will not overwrite if the destination file already exists.
            File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
        }

        // Catch exception if the file was already copied.
        catch (IOException copyError)
        {
            Console.WriteLine(copyError.Message);
        }
    }

    // Delete source files that were copied.
    foreach (string f in txtList)
    {
        File.Delete(f);
    }
    foreach (string f in picList)
    {
        File.Delete(f);
    }
}

catch (DirectoryNotFoundException dirNotFound)
{
    Console.WriteLine(dirNotFound.Message);
}

C# how to copy all files in a folder

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
 
namespace CopyDir
{
    class Program
    {
        static void Main(string[] args)
        {
            string FromDir = @"c:\source";
            string ToDir = @"c:\destination";
            if (!Directory.Exists(ToDir))
 
                Directory.CreateDirectory(ToDir);
 
            string[] Files;
            Files = Directory.GetFileSystemEntries(FromDir);
 
            for (int k = 0; k < Files.Length; k++)
            {
                string FromFile = Path.GetFileName(Files[k]);
 
                FileAttributes FileAttr = File.GetAttributes(Files[k]);
 
                if ((FileAttr & FileAttributes.Directory)== FileAttributes.Directory)
                    continue;
 
                Console.WriteLine(FromFile);
 
        string arrival = ToDir + "\\" + FromFile;
        File.Copy(Files[k], arrival, true);
                 
            }
            Console.ReadLine();
         }
    }
}