Memcached c# simple example

github link Install using nuget
 
PM> Install-Package EnyimMemcached
 
            MemcachedClientConfiguration config = new MemcachedClientConfiguration();
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("10.10.4.98"), 11211);
            config.Servers.Add(remoteEP);
            config.Protocol = MemcachedProtocol.Text;

            //using - not recommended here, check out documentation
            using (var mc = new MemcachedClient(config))
            {
                //get
                var zz = mc.Get("test_" + x);

                //set
                mc.Store(StoreMode.Set, "Test", "Hello World");
            }

Beanstalk simple example c#

https://github.com/sdether/libBeanstalk.NET download and compile
 
using Droog.Beanstalk.Client;
 
using (var client = new BeanstalkClient("10.10.4.99", 11300))
{
    var put = client.PutString("foo");
    var reserve = client.ReserveString();
    client.Delete(reserve.JobId);
}

Basic OID's values

SN, OID.2.5.4.4
G, OID.2.5.4.42
CN, OID.2.5.4.3
O, OID.2.5.4.10
T, OID.2.5.4.12
S, OID.2.5.4.9
OU, OID.2.5.4.11
L, OID.2.5.4.7

mvc 5 web api routing

 
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes(); 
    }
}
//using


    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        [Route("customers/orders")]
        [HttpGet]
        public string FindOrdersByCustomer() 
        {
            return "Supervalue";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }


http://www.codeproject.com/Articles/774807/Attribute-Routing-in-ASP-NET-MVC-WebAPI
http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

Simple AngularJS Application ( ASP.NET MVC + VS 2013 )

1 Create ASP.NET MVC Application

2 Create WebAPI
    public class MoviesController : ApiController
    {
        public IEnumerable Get()
        {
            return new List {
                new Movie {Id=1, Title="Star Wars", Director="Lucas"},
                new Movie {Id=2, Title="King Kong", Director="Jackson"},
                new Movie {Id=3, Title="Memento", Director="Nolan"}
            };
        }

        public string Get(int id)
        {
            return "value";
        }

        public void Post([FromBody]string value)
        {
        }

        public void Put(int id, [FromBody]string value)
        {
        }


        public void Delete(int id)
        {
        }
    }

3 Change Index.cshtml
@{
    ViewBag.Title = "Home Page";
}

@section scripts {


    }

Title Director
{{movie.Title}} {{movie.Director}}

4 Check result



wcf multithreading

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall, 
                 ConcurrencyMode=ConcurrencyMode.Single)] 

SignalR ASP NET Example

1 install nuget package


2 Add class Add | New Item | Visual C# | Web | SignalR | SignalR Hub Class (v2) 

3 Add Action to HomeController
4 Add view

5 Add Startup class
using Owin;
using Microsoft.Owin;
[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}

6 Test




OData + C#

1 Odata wcf Service

Create
https://msdn.microsoft.com/en-us/library/dd728275(v=vs.110).aspx

Get from browser
https://msdn.microsoft.com/en-us/library/dd728279(v=vs.110).aspx

Use
https://msdn.microsoft.com/en-US/library/dd728278(v=vs.110).aspx

2 OData WebAPI

Create
http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v3/creating-an-odata-endpoint

Use
http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v3/calling-an-odata-service-from-a-net-client

simple example reddis c#

1 Download MSI from here
https://github.com/MSOpenTech/redis/releases



2 Install nuget package in your project

3 How to use

using StackExchange.Redis;
//...
            using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("10.10.0.100:6379"))
            {
                IDatabase cache = redis.GetDatabase();

                cache.StringSet("key1", "value");
                cache.StringSet("key2", 25);

                string key1 = cache.StringGet("key1");
                int key2 = (int)cache.StringGet("key2");
            }

async await c# simple example

    public class MegaClass
    {
        public async void StartAsync()
        {
            await Task.Run(() => { LongProcedure(); });
            Console.WriteLine("End");
        }

        public void Start()
        {
            LongProcedure();
            Console.WriteLine("End");
        }

        private void LongProcedure()
        {
            Thread.Sleep(3000);
        }

        public async Task MyMethodAsync()
        {
            int x = await LongRunningOperationAsync();
            Console.WriteLine(x);
        }


        public async Task LongRunningOperationAsync() 
        {
            await Task.Delay(3000); 
            return 1;
        }

        public async Task LongRunningOperationAsync(int _param)
        {
            await Task.Delay(3000);
            return _param;
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            var _c = new MegaClass();

            //1 Sync
            //_c.Start();

            //2 Async
            //c.StartAsync();

            //3 Start and return task
            //Task t = _c.MyMethodAsync();
            //t.Wait();

            //4
            //Task task = new Task(_c.StartAsync);
            //task.Start();

            //5 GetResult 
            //Task x = _c.LongRunningOperationAsync();
            //x.Wait();
            //Console.WriteLine(x.Result);

            //6 with param
            //Task x = _c.LongRunningOperationAsync(3);
            //x.Wait();
            //Console.WriteLine(x.Result);

            Console.WriteLine("Wait");
            Console.ReadLine();
        }
    }

c# Simple socket example


client
    public class SynchronousSocketClient
    {

        public static void StartClient()
        {
            byte[] bytes = new byte[4096];

            try
            {
                IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

                Socket sender = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream, ProtocolType.Tcp);

                try
                {
                    sender.Connect(remoteEP);

                    Console.WriteLine("Socket connected to {0}",
                        sender.RemoteEndPoint.ToString());

                    byte[] msg = Encoding.UTF8.GetBytes("TEST MSG!EOF");

                    int bytesSent = sender.Send(msg);

                    int bytesRec = sender.Receive(bytes);
                    Console.WriteLine("Echoed test = {0}",
                        Encoding.UTF8.GetString(bytes, 0, bytesRec)
                        );

                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();

                }
                catch (ArgumentNullException ane)
                {
                    Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
                }
                catch (SocketException se)
                {
                    Console.WriteLine("SocketException : {0}", se.ToString());
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }


    }
server
    public class SynchronousSocketListener
    {

        public static string data = null;

        public static void StartListening()
        {
            byte[] bytes = new Byte[4096];

            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

            Socket listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                while (true)
                {
                    Console.WriteLine("Waiting for a connection...");
                    Socket handler = listener.Accept();
                    data = null;

                    while (true)
                    {
                        bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes);
                        data += Encoding.UTF8.GetString(bytes, 0, bytesRec);
                        if (data.IndexOf("!EOF") > -1)
                        {
                            break;
                        }
                    }


                    Console.WriteLine("Text received : {0}", data);

                    byte[] msg = Encoding.UTF8.GetBytes(data);

                    handler.Send(msg);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();

        }

    }
test console
    class Program
    {
        static void Main(string[] args)
        {

            Task.Factory.StartNew(() => SynchronousSocketListener.StartListening());
            Thread.Sleep(2000);
            Task.Factory.StartNew(() => SynchronousSocketClient.StartClient());
            Console.Read();
            Task.Factory.StartNew(() => SynchronousSocketClient.StartClient());
            Console.Read();
            Task.Factory.StartNew(() => SynchronousSocketClient.StartClient());
            Console.Read();
        }
    }

allowed clock skew is '00:05:00'



I had the same issue and followed all recommendations. But my fault was that I changed only server configuration, whereas I had to change client configuration too.
This is my config without maxClockSkew
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <connectionStrings>
    <!-- -->
  </connectionStrings>
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_IHotLine1" closeTimeout="00:10:00"
          openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
          maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
            maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security>
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="localhost:6767/blabla.svc" binding="wsHttpBinding"
        bindingConfiguration="WSHttpBinding_IHotLine1" contract="ServiceReference2.IHotLine"
        name="WSHttpBinding_IHotLine1">
        <identity>
          <certificate encodedValue="====encodedvalue===" />
        </identity>
      </endpoint>
    </client>
  </system.serviceModel>
</configuration>
And updated with clock skew
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.serviceModel>
    <bindings>
      <customBinding>
        <binding name="WSHttpBinding_IHotLine1">
          <transactionFlow/>
          <security authenticationMode="SecureConversation"
messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10">
            <localClientSettings maxClockSkew="01:30:00" />
            <localServiceSettings maxClockSkew="01:30:00" />
            <secureConversationBootstrap authenticationMode="UserNameForSslNegotiated"
messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10" >
              <localClientSettings maxClockSkew="01:30:00" />
              <localServiceSettings maxClockSkew="01:30:00" />
            </secureConversationBootstrap>
          </security>
          <textMessageEncoding/>
          <httpTransport maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
        </binding>
      </customBinding>
    </bindings>
    <client>

      <endpoint address="http://localhost:6767/blabla.svc" binding="customBinding"
        bindingConfiguration="WSHttpBinding_IHotLine1" contract="ServiceReference2.IHotLine"
        name="WSHttpBinding_IHotLine1">
        <identity>
          <certificate encodedValue="====encodedva

json javascriptserializer length error

        protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
        {
            return new JsonResult()
            {
                Data = data,
                ContentType = contentType,
                ContentEncoding = contentEncoding,
                JsonRequestBehavior = behavior,
                MaxJsonLength = Int32.MaxValue
            };
        }

c# check either work or not service on a remote computer

 
using System.Management;

       static bool ServiceIsRunning(string ServiceName)
        {
            ConnectionOptions op = new ConnectionOptions();
            op.Username = "domain\\username";
            op.Password = "password";
            ManagementScope scope = new ManagementScope("\\\\OLAP1\\root\\cimv2", op);
            scope.Connect();

            string objPath = string.Format("Win32_Service.Name='{0}'", "SubscribeReportService");
            using (ManagementObject service = new ManagementObject(scope, new ManagementPath(objPath), null))
            {
                if (service.GetPropertyValue("State").ToString() == "Running")
                    return true;
                else
                    return false;
            }
        }

http://stackoverflow.com/questions/1335065/check-status-of-services-that-run-in-a-remote-computer-using-c-sharp

Good article about possible solutions for creating WEB DataTables

http://www.sitepoint.com/responsive-data-tables-comprehensive-list-solutions/

react js
http://adazzle.github.io/react-data-grid/examples.html#/basic

c# Reading file occurs The process cannot access the file 'Path' because it is being used by another process.

                using(var fs = new System.IO.FileStream(@"Path", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
                using (var sr = new System.IO.StreamReader(fs))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(line);
                    }
                }

If you just need whole text not lines, then use this code for better performance
                            using (var fs = new System.IO.FileStream(res.path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
                            using (var sr = new System.IO.StreamReader(fs))
                            {
                                return sr.ReadToEnd();
                            }

WCF IP in adress not Computer name

just add this line in system.serviceModel
  
    
  

Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

 
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;

namespace YourNameSpace
{
    /// 
    /// Provides access to a network share.
    /// 
    public class NetworkShareAccesser : IDisposable
    {
        private string _remoteUncName;
        private string _remoteComputerName;

        public string RemoteComputerName
        {
            get
            {
                return this._remoteComputerName;
            }
            set
            {
                this._remoteComputerName = value;
                this._remoteUncName = @"\\" + this._remoteComputerName;
            }
        }

        public string UserName
        {
            get;
            set;
        }
        public string Password
        {
            get;
            set;
        }

        #region Consts

        private const int RESOURCE_CONNECTED = 0x00000001;
        private const int RESOURCE_GLOBALNET = 0x00000002;
        private const int RESOURCE_REMEMBERED = 0x00000003;

        private const int RESOURCETYPE_ANY = 0x00000000;
        private const int RESOURCETYPE_DISK = 0x00000001;
        private const int RESOURCETYPE_PRINT = 0x00000002;

        private const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000;
        private const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
        private const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002;
        private const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003;
        private const int RESOURCEDISPLAYTYPE_FILE = 0x00000004;
        private const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005;

        private const int RESOURCEUSAGE_CONNECTABLE = 0x00000001;
        private const int RESOURCEUSAGE_CONTAINER = 0x00000002;


        private const int CONNECT_INTERACTIVE = 0x00000008;
        private const int CONNECT_PROMPT = 0x00000010;
        private const int CONNECT_REDIRECT = 0x00000080;
        private const int CONNECT_UPDATE_PROFILE = 0x00000001;
        private const int CONNECT_COMMANDLINE = 0x00000800;
        private const int CONNECT_CMD_SAVECRED = 0x00001000;

        private const int CONNECT_LOCALDRIVE = 0x00000100;

        #endregion

        #region Errors

        private const int NO_ERROR = 0;

        private const int ERROR_ACCESS_DENIED = 5;
        private const int ERROR_ALREADY_ASSIGNED = 85;
        private const int ERROR_BAD_DEVICE = 1200;
        private const int ERROR_BAD_NET_NAME = 67;
        private const int ERROR_BAD_PROVIDER = 1204;
        private const int ERROR_CANCELLED = 1223;
        private const int ERROR_EXTENDED_ERROR = 1208;
        private const int ERROR_INVALID_ADDRESS = 487;
        private const int ERROR_INVALID_PARAMETER = 87;
        private const int ERROR_INVALID_PASSWORD = 1216;
        private const int ERROR_MORE_DATA = 234;
        private const int ERROR_NO_MORE_ITEMS = 259;
        private const int ERROR_NO_NET_OR_BAD_PATH = 1203;
        private const int ERROR_NO_NETWORK = 1222;

        private const int ERROR_BAD_PROFILE = 1206;
        private const int ERROR_CANNOT_OPEN_PROFILE = 1205;
        private const int ERROR_DEVICE_IN_USE = 2404;
        private const int ERROR_NOT_CONNECTED = 2250;
        private const int ERROR_OPEN_FILES = 2401;

        #endregion

        #region PInvoke Signatures

        [DllImport("Mpr.dll")]
        private static extern int WNetUseConnection(
            IntPtr hwndOwner,
            NETRESOURCE lpNetResource,
            string lpPassword,
            string lpUserID,
            int dwFlags,
            string lpAccessName,
            string lpBufferSize,
            string lpResult
            );

        [DllImport("Mpr.dll")]
        private static extern int WNetCancelConnection2(
            string lpName,
            int dwFlags,
            bool fForce
            );

        [StructLayout(LayoutKind.Sequential)]
        private class NETRESOURCE
        {
            public int dwScope = 0;
            public int dwType = 0;
            public int dwDisplayType = 0;
            public int dwUsage = 0;
            public string lpLocalName = "";
            public string lpRemoteName = "";
            public string lpComment = "";
            public string lpProvider = "";
        }

        #endregion

        /// 
        /// Creates a NetworkShareAccesser for the given computer name. The user will be promted to enter credentials
        /// 
        /// 
        /// 
        public static NetworkShareAccesser Access(string remoteComputerName)
        {
            return new NetworkShareAccesser(remoteComputerName);
        }

        /// 
        /// Creates a NetworkShareAccesser for the given computer name using the given domain/computer name, username and password
        /// 
        /// 
        /// 
        /// 
        /// 
        public static NetworkShareAccesser Access(string remoteComputerName, string domainOrComuterName, string userName, string password)
        {
            return new NetworkShareAccesser(remoteComputerName,
                                            domainOrComuterName + @"\" + userName,
                                            password);
        }

        /// 
        /// Creates a NetworkShareAccesser for the given computer name using the given username (format: domainOrComputername\Username) and password
        /// 
        /// 
        /// 
        /// 
        public static NetworkShareAccesser Access(string remoteComputerName, string userName, string password)
        {
            return new NetworkShareAccesser(remoteComputerName,
                                            userName,
                                            password);
        }

        private NetworkShareAccesser(string remoteComputerName)
        {
            RemoteComputerName = remoteComputerName;

            this.ConnectToShare(this._remoteUncName, null, null, true);
        }

        private NetworkShareAccesser(string remoteComputerName, string userName, string password)
        {
            RemoteComputerName = remoteComputerName;
            UserName = userName;
            Password = password;

            this.ConnectToShare(this._remoteUncName, this.UserName, this.Password, false);
        }

        private void ConnectToShare(string remoteUnc, string username, string password, bool promptUser)
        {
            NETRESOURCE nr = new NETRESOURCE
            {
                dwType = RESOURCETYPE_DISK,
                lpRemoteName = remoteUnc
            };

            int result;
            if (promptUser)
            {
                result = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
            }
            else
            {
                result = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);
            }

            if (result != NO_ERROR)
            {
                throw new Win32Exception(result);
            }
        }

        private void DisconnectFromShare(string remoteUnc)
        {
            int result = WNetCancelConnection2(remoteUnc, CONNECT_UPDATE_PROFILE, false);
            if (result != NO_ERROR)
            {
                throw new Win32Exception(result);
            }
        }

        /// 
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// 
        /// 2
        public void Dispose()
        {
            this.DisconnectFromShare(this._remoteUncName);
        }
    }
}

using
 
                        using (NetworkShareAccesser.Access(server, Config.Domain, Config.User, Config.Pass))
                        {

                            return System.IO.File.ReadAllText(res.path);
                        }

ASP NET Compression Caching

modify web.config
  
    
      
    
    
      
    
    
      
      
        
        
        
        
        
        
        
      
      
        
        
        
        
        
        
        
      
    
    
  
add attribute where it requers
        [OutputCache(Duration = int.MaxValue, VaryByParam = "none")]
        public ActionResult Index()
        {
            return View();
        }

ASP .NET MVC 5 Validation and Way to change standard validation message

my view
@model Riski.Models.Koef

@using (Html.BeginForm()) {
    

    @Html.AntiForgeryToken()
    

@Model.name


@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.LabelFor(model => model.koef1, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.koef1, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.koef1, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.id) @Html.HiddenFor(model => model.name)
}
@Html.ActionLink("Вернуться к списку", "Index")
@section scripts{ @Scripts.Render("~/bundles/jqueryval") }
my controller
        [HttpPost]
        public ActionResult Edit(Koef koef)
        {
            if (ModelState.IsValid)
            {
                db.Configuration.ValidateOnSaveEnabled = false;

                db.Koefs.Attach(koef);
                var entry = db.Entry(koef);
                entry.Property(e => e.koef1).IsModified = true;

                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(koef);
        }
this is a partial class wich helps us to validate our model. Acording to this approach we don't need to add Validation Attributies after every process of generation Entity classes
using System;
using System.ComponentModel.DataAnnotations;

namespace Riski.Models
{
    [MetadataType(typeof(KoefViewModel))]
    public partial class Koef
    {
    }

    public class KoefViewModel
    {
        [Required]
        [Display(Name = "Коэффициент")]
        [Range(0, 100, ErrorMessage = "Значение должно быть от 0 до 100.")]
        public Nullable koef1 { get; set; }

        [Required]
        public int id { get; set; }
    }
}
That's it. Now , as this is a russian web-site, we need to override some standard validation messages. It's simple solution and we should do only for steps

1 Add folder

2 Create resource file

3 Add new value (We can override 4 types of messages FieldMustBeDateFieldMustBeNumericPropertyValueInvalid andPropertyValueRequired)


4 And add one line to your Global.asax.cs
DefaultModelBinder.ResourceClassKey = "MyNewResource";

Creating stub methods using ShortCut in VS2013

http://dailydotnettips.com/2011/01/01/generate-method-stubs-using-shortcut-key-in-visual-studio/

just press "ctrl + ." and "Enter"

c# run thread in threadpool

This is the way of running thread in ThreadPool
1 only for 4.5 Framework
Task.Run(() => doStuff("hello world"));
2
Task.Factory.StartNew(() => doStuff("hello world"));
3
ThreadPool.QueueUserWorkItem(a => doStuff("hello world"));
4
void Example()
{
    // Hook up the ProcessFile method to the ThreadPool.
    // Note: 'a' is an argument name. Read more on arguments.
    ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessFile), a);
}

private void ProcessFile(object a)
{
    // I was hooked up to the ThreadPool by WaitCallback.
}

sql management studio allow drop and recreate


EntityFramework exec proc with out params


using (var db = new MyEntities())
{
    var Owner_ID = new ObjectParameter("Owner_ID", typeof(string));
    var msgError = new ObjectParameter("msgError", typeof(string));
    db.InsBeerClient(Owner_ID, msgError);
    return (msgError.Value ?? "").ToString();
}

Entity Framework Update

You can easly do it by using this code


using (var db = new EGAIS_RUEntities())
            {
                db.Configuration.ValidateOnSaveEnabled = false;
                var _rec = new CONTRAGENT()
                {
                    id = 1,
                    status = 3
                };

                db.CONTRAGENTS.Attach(_rec);
                var entry = db.Entry(_rec);
                entry.Property(e => e.status).IsModified = true;
                db.SaveChanges();
            }

Please note, I set only value, that i wanted to cahnge. Another value is "id", that identifies the record.

Another interesting aspect is this

db.Configuration.ValidateOnSaveEnabled = false;

You will get an error if you don't set the fields with NOTNULL values.

another approach to it is
dbcontext.Entry(_rec).State = System.Data.Entity.EntityState.Modified;
dbcontext.SaveChanges();

с# get GOST 3410 certificate from container

public static X509Certificate2 GetCertFromCont(string pin, string CertCont)
        {
            CspParameters cspParameters = new CspParameters(75);
            cspParameters.KeyContainerName = CertCont;
            cspParameters.Flags = CspProviderFlags.NoPrompt;
 
 
 
            if (pin != "")
            {
                System.Security.SecureString s = new System.Security.SecureString();
                foreach (char z in pin)
                    s.AppendChar(z);
                cspParameters.KeyPassword = s;
            }
 
            try
            {
                Gost3410CryptoServiceProvider prov = new Gost3410CryptoServiceProvider(
                    cspParameters);
                return prov.ContainerCertificate;
            }
            catch (Exception e)
            {
                //System.Windows.MessageBox.Show(e.Message);
                return null;
            }
 
        }

VS2010 tfs http code 203 non-authoritative information

1 Service Pack 1 for Visual Studio 2010

2 Visual Studio 2010 SP1 Team Foundation Server 2012 Compatibility GDR - This patch found here

Introdution example from KnockoutJs

//HTML
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>

<p>Full name: <strong data-bind="text: fullName"></strong></p>

<button data-bind="click: capitalizeLastName">Go caps</button>

----------------------------------------------------------------------

//JS
function AppViewModel({
    this.firstName ko.observable("Bert");
    this.lastName ko.observable("Bertington");
    
    this.fullName ko.computed(function({
    return this.firstName(" " this.lastName();    
    }this);
    
    this.capitalizeLastName function({
        var currentVal this.lastName();        // Read the current value
        this.lastName(currentVal.toUpperCase())// Write back a modified value
    };
}

ko.applyBindings(new AppViewModel());




Download KnockOutJS