WCF без config файла - CodeHelper

WCF без config файла

2

Нужен пример простого сервиса, исмользующего wsDualHttpBindng и поддерживающего шифрвание на уровне сообщений. Сервис уже есть, для него студией генерируется прокси и конфиг файл. Интересует как теперь запихнуть конфиг внутрь прокси ?

Код для сервиса

        // ищем нужный сертификат в хранилище
        X509Certificate2 cert = null;
        X509Store certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        certStore.Open(OpenFlags.ReadOnly);
        for (int i = 0; i < certStore.Certificates.Count; i++)
            if (certStore.Certificates[i].SubjectName.Name == "CN=testsvc")
                cert = certStore.Certificates[i];
        certStore.Close();

        WSDualHttpBinding binding = new WSDualHttpBinding(WSDualHttpSecurityMode.Message);
        binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
        binding.MaxReceivedMessageSize = Int32.MaxValue;

        // устанавливаем параметры аутентификации
        _AdminHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
        _AdminHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new AdminUserNameValidator();

        // указываем используемый сертификат
        // _AdminHost - это хост
        _AdminHost.Credentials.ServiceCertificate.Certificate = cert;

        // наша конечная точка
        _AdminHost.AddServiceEndpoint(typeof(IServiceAdmin),
            binding,
            new Uri("http://localhost:999/ServiceAdmin"));

        // mex
        _AdminHost.Description.Behaviors.Add(new ServiceMetadataBehavior());
        Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding();
        _AdminHost.AddServiceEndpoint(typeof(IMetadataExchange),
            mexBinding,
            new Uri("http://localhost:999/ServiceAdmin/mex"));

Как создать аналогичную картину (без конфига) на клиенте??

Лучший ответ:

2

Отвечаю сам себе

        WSDualHttpBinding binding = new WSDualHttpBinding(WSDualHttpSecurityMode.Message);
        binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
        binding.MaxReceivedMessageSize = Int32.MaxValue;

        // ищем cертификат .cer для сервера в TrustedPeople
        X509Certificate2 cert = null;
        X509Store certStore = new X509Store(StoreName.TrustedPeople, StoreLocation.CurrentUser);
        certStore.Open(OpenFlags.ReadOnly);
        for (int i = 0; i < certStore.Certificates.Count; i++)
            if (certStore.Certificates[i].SubjectName.Name == "CN=testsvc")
                cert = certStore.Certificates[i];
        certStore.Close();

        // указываем identity по сертификату
        X509CertificateEndpointIdentity identity = new X509CertificateEndpointIdentity(cert);

        // адрес
        EndpointAddress addr = new EndpointAddress(new Uri("http://localhost:999/ServiceAdmin"),
            identity,
            new AddressHeaderCollection());

        // это коллбек
        _ClientCallback = new ServiceAdminCallback();

        // это клиент
        Client = new ServiceAdminClient(new InstanceContext(_ClientCallback),
            binding,
            addr);

        Client.ClientCredentials.UserName.UserName = _LastUser;
        Client.ClientCredentials.UserName.Password = _LastPassword;

Вот так. И никаких конфигов ;) PS. В этом примере реализовано только шифрование сообщений серверу

Новые ответы

Новые Лучшие

0

Приветствую. Извиняюсь что не в тему. Может у кого нибудь есть ландшафтный дизайнер или дизайнер по интерьеру.Буду очень признателен за помощь. Контакты можно найти на нашем сайте: http://mydecorshop.ru

0

[url=http://www.cheapeucigarettes.com/#cigarettes][img]http://www.cheapeucigarettes.com/cigarettes.gif[/img][/url]

a cold and wet place under a cold and wet astrological sign, she or he might wish to consult a physician in advance for advice about adjusting diet, exercise, rest, evacuation patterns, and passions so as to minimize the tendency to imbalance, and, hence, illness. This is what the Greek physician Galen (129-199 c.e.), who codified humoral theory, termed the "non-naturals." [url=http://toloveru.fr/spip.php?page=forum&id_breve=197/]Dunhill cw1h[/url] Pursh. 2: 532, 657-658 slaves as chattel, 1: 124 task system in, 2: 657 tobacco processing by, 1: 293; 2: 530 tobacco revolution and, [url=http://www.cheapeucigarettes.com/cheap-cigarettes/camel-natural-flavor-6.html#a56h]Camel Natural Flavor 6 Cigarettes[/url] tobacco, 2: 641-642 export of tobacco from New Many experts believe that the answer to this very sensible question is that prohibition would not work. Almost 50 million adults smoke. Most of these tobacco users are addicted to the nicotine in tobacco. These people would still be dependent on nicotine if tobacco sales were made illegal. Experts fear that, as was the case when alcohol sales were made illegal in the early twentieth century, a black market for tobacco prod-ucts would quickly come into existence. [url=http://forum.newresidence.ru/viewtopic.php?pid=20212#p20212]Cheap Cigarettes c56x[/url]

0

[url="http://www.cheaponlineviagra.org/buyviagranow.html"][img]http://www.viagracollection.com/Viagra-x.gif[/img][/url]

Baker's cyst A fluid-filled swelling that develops behind the knee, also called a popliteal cyst. It gets its name from the doctor who first described it. A Baker's cyst develops in response to repeated irritation that inflames the knee joint, such as might occur with repetitious action, OSTEOARTHRITIS, or RHEUMATOID ARTHRITIS. Some men experience pain and restricted movement of the knee or swelling of the calf just below the knee, and others have no symptoms. Large Baker's cysts that cause pressure on the blood vessels running through the knee area can cause DEEP VEIN THROMBOSIS (DVT), a serious condition in which blood clots form in the veins of the lower legs. [url=http://forums.ext.net/index.php] Buy Viagra l Buy Viagra Online[/url] diabetes and 111 dialysis for 113-115 nonsteroidal anti-inflammatory [url=http://www.sunfax-co.com/enguestbook01.php?PHPSESSID=bb256d5683b40d52270fc0f8e3a4c9ec]Medicines for Men - Cialis a31z[/url] immunosuppressive therapy 177 for inflammatory bowel disease 184 [url=http://tgel62.free.fr/phpBB2/profile.php?mode=viewprofile&u=269&sid=96c1732e9af46283bb25c02b4d95c294]Medicines for Men k51h[/url] dyslipidemia See HYPERLIPIDEMIA. [url=http://www.viagracollection.com/viagra-online/how-to-buy-viagra-for-women-online/#b37h]Viagra [/url] Treatment is immediate surgical removal of the testicle through an inguinal (groin) incision (inguinal ORCHIECTOMY), extracting the testicle up from within the scrotum and away from its blood supply to minimize disruption of the tumor or bleeding that could disperse cancer cells into the bloodstream. If the doctor suspects the cancer may have spread to the lymph nodes (more likely with nonseminomas), surgery includes removal of the adjacent groin and perhaps the retroperitoneal lymph nodes located along the back wall of the abdomen. Surgery to remove lymph nodes often is a second operation. ULTRASOUND or a COMPUTED TOMOGRAPHY (CT) Restriction rings. A restriction ring is a band that goes around the base of the penis that becomes tight with erection. it slows the flow of blood out of the penis, helping to sustain the erection. often a restriction ring is used in combination with other mechanical methods. [url=http://www.runwayvixens.com/forum/showthread.php?p=113930#post113930] Buy Viagra kr7z[/url] varicocele and 337 sperm count 298 spermicides 99 sperm morphology 298 sperm motility 298, 311 sphygmomanometer 55, 169 spinal cord 228-229 spinal cord injury 229, 311-312 athletic activities and 38 post void residual volume and 272 spinal nerves 228 spine, structure and function of 41 spironolactone 30, 116 spleen [url=http://www.objectif-rallye-historique.com/forum.php3?idarticle=110]Viagra Online b37z[/url] Actions that are compulsive and demanding of others and that provoke confrontation and discord

0

facts about Marlboro Cigarettes [url=http://www.1000websitetoools.com/interesting-facts-about-marlboro-cigarettes/#aq7z]facts about Marlboro Cigarettes[/url] Marlboro Reds

0

Localization of erythropoietin synthesizing cells in murine kidneys by in situ hybridizatioBlood 71, 524-527. [url=http://refine.eecs.ucf.edu/gf/project/plcwhat/scmsvn/?action=browse&path=%2Ftrunk%2FPLCWhat%2Facmprocarticle-sp.cls&revision=38&sortdir=down&view=markup] Buy Viagra l Buy Viagra Online[/url] The antitumor efficacy of this agent against human prostate cancer cells injected into nude mice will be dictated by the host, rather than by the cells. [url=http://www.masako.es/blog/?attachmentid=159#comment-23598]Medicines for Men aq1h[/url] CO(CH2)6CHa Gly-Ser-Ser-Phe-Lys-Ser-Pro-Glu-His-Glu-Lys-Ala-Glu-Glu-Arg-Lys-Asp-Ser-Lys-Lys- Pro-Pro-Ala-Lys-Leu-Glu-Pro-ArCO(CH2)6CHb Gly-Ser-Ser-Phe-Lys-Ser-Pro-Glu-His-Glu-Lys-Ala-Glu-Arg-Lys-Asp-Ser-Lys-Lys-Pro-Pro- Ala-Lys-Leu-Glu-Pro-ArFIGURE 1 Amino acid sequences of (a) rat ghrelin-28 and (b) des-Gln14-ghreli [url=http://forum.verooom.com/memberlist.php?mode=viewprofile&u=8692] Cialis, Cialis Super Active, Cialis Professional b51h[/url] These hormones bind to receptors on the gonads, the ovaries, and testes, and individually influence either sex steroid production (primarily luteinizing hormone) or the development of eggs and sperG-protein-coupled receptors Membrane receptors, also called seven-transmembrane, or serpentine, receptors; bind peptides or small molecules on the cell surface and bind intracellularly with small three-subunit G-pro- teins, the activity of which is regulated by GTP cleavage and phosphorylatioThe Ga subunit communicates directly with and activates other intracellular signaling cascades to increase levels of cyclic AMP, phospholi- pids, and intracellular Ca2+ [url=http://www.insetcards.com/viagra-super-active-capsules-ultimate-effect/#dw1h]Viagra Super Active online[/url] site further upstreaThe CCAAT site has been demonstrated to bind the transcription factors MSY- 1 and NF-Y The lower the magnitude of Kd, the greater the affinity between ligand and receptoreceptor recycling Movement of a receptor from ainternal compartment to the cell surfacRGS proteins (regulators of G-protein signaling proteins) Effectors that act as guanosine triphosphatase-activat- ing proteins, enhancing the rate of GTP hydrolysis by Ga subunits. [url=http://www.gonouvellezelande.fr/forum/viewtopic.php?f=3&t=35526]Cheap Viagra d51z[/url] Gerich, J., Charles, M., and Grodsky, (1974) [url=http://www.kerben.org/modules/news/replycomment.php?commentid=2808&mode=flat&order=0]Buy Viagra online aw6h[/url] Although many of the details remain unclear, starvation inhibits hypo- thalamic neurons (e.g., thyrotropin-releasing hor¬mone neurons) that would otherwise stimulate the secretion of anterior pituitary factors (e.g., thyroid- stimulating hormone), which would in turn stimulate endocrine end organs (e.g., thyroid gland) (Fi3)

0

Я присоединяюсь ко всему выше сказанному. тел 044-383-14-05 http://megasto.com.ua/rihtovochnye-stendy/ Рихтовочные стенды


v1.7.123.556
© 2009—2010 CodeHelper FAQ | О сайте | Обратная связь | История изменений | Статьи
Creative Commons LicenseМатериалы сайта распространяются под лицензией Creative Commons Attribution-Share Alike 3.0 Unported.