8 Temmuz 2016 Cuma

MVC project Add Web Api

Update the MVC project

Use Nuget to get the newest Web API.
Project - Right click - Manage Nuget Packages - Search for Web API (Microsoft ASP.NET Web API ...) and install it to your MVC project.
Then you still need to get Web API routing to work. From

Add WebApiConfig.cs to the App_Start/ folder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WebApplication1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // TODO: Add any additional configuration code.

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

        // WebAPI when dealing with JSON & JavaScript!
        // Setup json serialization to serialize classes to camel (std. Json format)
        var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        formatter.SerializerSettings.ContractResolver =
            new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();

        }
    }
}
If you have an MVC Project it will have Global.asax.cs, add the new routes. Order of the Global.asax.cs routes is critical. Note there are outdated examples which use WebApiConfig.Register
Add this line to Global.asax.cs: GlobalConfiguration.Configure(WebApiConfig.Register);
        // Default stuff
        AreaRegistration.RegisterAllAreas();

        // Manually installed WebAPI 2.2 after making an MVC project.
        GlobalConfiguration.Configure(WebApiConfig.Register); // NEW way
        //WebApiConfig.Register(GlobalConfiguration.Configuration); // DEPRECATED

        // Default stuff
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

WebAPI Help


To verify WebAPI is working:

To the controllers folder -> Add new item -> Web API Controller Class.
public class TestController : ApiController
{
    //public TestController() { }

    // GET api/<controller>
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }
    //...
}
Now you can test in IE/FF/Chrome as usual, or in the JavaScript consoles for non-get testing.
(With just the controller in the URL it will call the GET() action in the new Web API Controller, it's automatically mapped to methods/actions depending on the REST e.g. PUT/POST/GET/DELETE. You don't need to call them by action like in MVC) The URL directly:
http://localhost:PORT/api/CONTROLLERNAME/
Alternatively use jQuery to query the controller. Run the project, Open the console (F12 in IE) and try run an Ajax query. (Check your PORT & CONTROLLERNAME)
$.get( "http://localhost:PORT/api/CONTROLLERNAME/", function( data ) {
    //$( ".result" ).html( data );
    alert( "Get data received:" + data);
});

8 Şubat 2016 Pazartesi

Could not load file or assembly Microsoft.ReportViewer.WebForms or one of its dependencies

Benim hatam 10. versiyonda idi onun için https://www.microsoft.com/en-us/download/confirmation.aspx?id=6442 adresinden indiriyorum ve sonar problem çözülüyor

23 Aralık 2015 Çarşamba

Select into ve Insert into arasındaki fark

Eğer tablo tanımlı değilse
select into Table_1 select * from Table_2

kullanıyoruz.

Tanımlı ise;

insert into Table_1 select * from Table_2

kullanıyoruz.

Burada dikkat edilmesi gereken durumlar select into da PK, FK, index'ler ve triggerlar otomatik oluşmamakaadır.Bunun için create scriptlerini çalıştırmak gerekiyor.

16 Aralık 2015 Çarşamba

C# Exception Hatalarını Anlamlı Hale Getirmek

try
{
throw new Exception();

}
catch (Exception ex)
{
// Get stack trace for the exception with source file information

int lineNumber = (new System.Diagnostics.StackFrame(0, true)).GetFileLineNumber();
var columnNumber = (new System.Diagnostics.StackFrame(0, true)).GetFileColumnNumber();

  
var strName = System.IO.Path.GetFileName((new System.Diagnostics.StackFrame(0, true)).GetFileName());

MessageBox.Show(strName);
}

C#'da Çokça Kullanacağınız Dosya ile İlgili İşlemler

*Programınızda geçici olarak dosya kaydetme ve görüntüleme için bu dizini kullanabilirsiniz.İzin gerektirmeden işlemlerinizi yapabilirsiniz.

string folder = Environment.GetEnvironmentVariable"TEMP");
//C:\Users\username*\AppData\Local\Temp *username Windows kullancının adı

*Programınızın çalıştığı dizini almak için bunu kullanabilişiniz.Config dosyalarını buraya koyabilirsiniz.

 string LocalPath = new Uri(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).LocalPath;

*Programınız çalışırken klasör oluşturmak için

string fullPAth = LocalPath + Guid.NewGuid().ToString();

if (!Directory.Exists(fullPAth)
{  rectoryInfo di = Directory.CreateDirectory(fullPAth);
}

*Programınızda dizine dosya yazmak için
 
public byte[] AttachmentData { get; set; }
File.WriteAllBytes((fullPAth + \\data.txt), AttachmentData);


*Programınızda dizindeki dosyanın adını

string path = "C:\Sources\bin\Debug\1.pdf";
string fileName = System.IO.Path.GetFileName(path ); 
 
\\\\1.pdf ismini geri dönecektir

*Programınızda dizindeki dosyanın uzantısını almak için

string file_extention = System.IO.Path.GetExtension(files.FileName).Trim().ToLower();
 

 

25 Kasım 2015 Çarşamba

WCF SecurityNegotiationException Hatası


"Unhandled Exception: System.ServiceModel.Security.SecurityNegotiationException: Secure channel cannot be opened because security negotiation with the remote endpoint has failed. This may be due to absent or incorrectly specified EndpointIdentity in the EndpointAddress used to create the channel. Please verify the EndpointIdentity specified or implied by the EndpointAddress correctly identifies the remote endpoint. ---> System.ServiceModel.FaultException: The message with Action 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None)."

Hatasını aldığınızda Enpoint adresinde bazı security, mesaj ve Transport ayarlarından dolayı hata almaktasınız.Bu servisin yapısına göre değişkenlik gösterebilir.

Bir windows web servis için yaptığımız configurasyon örneği aşağıdaki gibidir

System.ServiceModel.WSHttpBinding binding = new System.ServiceModel.WSHttpBinding();



binding.MaxReceivedMessageSize = 2147483647;
binding.CloseTimeout = TimeSpan.MaxValue;
binding.OpenTimeout = TimeSpan.MaxValue;
binding.ReceiveTimeout = TimeSpan.MaxValue;
binding.SendTimeout = TimeSpan.MaxValue;

WSHttpSecurity _wsHttpSecurity = new WSHttpSecurity();
_wsHttpSecurity.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
_wsHttpSecurity.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
_wsHttpSecurity.Transport.Realm = "";

_wsHttpSecurity.Message.ClientCredentialType = MessageCredentialType.Windows;
_wsHttpSecurity.Message.NegotiateServiceCredential = true;
_wsHttpSecurity.Message.EstablishSecurityContext = true;

_wsHttpSecurity.Mode = SecurityMode.None;



binding.Security = _wsHttpSecurity;
.
EndpointAddress endpointAddress = new EndpointAddress("***/Retrieval.svc"); //Live


RetrievallWS.RetrievalClient retrievallWS = new RetrievallWS.RetrievalClient(binding, endpointAddress);


          

WCF Maximum Message Size Hatası

Bu hatayı her zaman değil servisten çekilen verinin boyutu 65536'ten büyük ise almaktasınız.

Hata metni aşağıdaki gibi ise;

"The maximum message size quota for incoming messages (65536) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element."

servisi şu şekilde değiştirmeniz gerekmektedir.


<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="****" allowCookies="true" maxBufferPoolSize="2147483647"
maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="2147483647" />
</binding>
<binding name="****1" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="*****"
binding="basicHttpBinding" bindingConfiguration="****"
contract="**.**" name="*****" />
<endpoint address="***" binding="basicHttpBinding"
bindingConfiguration="KodAYSWebServiceSoap1" contract="**.**"
name="WebServiceSoap1" />
</client>
</system.serviceModel>