Wednesday, December 14, 2011

In c# WSE security

First,Install WSE 2. From Microsoft.


Before you call for service;



svc.RequestSoapContext.Security.Tokens.Add(new UsernameToken(UserName, Password, PasswordOption.SendPlainText));

Why did not write Nlog to targets


In  NLog.config write nlog tabs; throwExceptions="true" internalLogFile="c:\nlog.txt" internalLogLevel="Trace" 

like;


<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwExceptions="true" internalLogFile="c:\nlog.txt" internalLogLevel="Trace" >

Monday, November 28, 2011

Basic Authentication


protected override System.Net.WebRequest GetWebRequest(Uri uri)
        {
            string pass = "pass" + ":" + "****";           
            var key = Convert.ToBase64String(new System.Text.ASCIIEncoding().GetBytes(pass));
            var basicKey= "Basic " + key;
            var getWebRequest = base.GetWebRequest(uri);          
            getWebRequest.Headers.Add("authorization", basicKey);
            return getWebRequest;
        }

Wednesday, November 2, 2011

The remote server returned an error: (404) Not Found

In web.config file, change endpoint address http to basic

Tuesday, October 11, 2011

InArgument and OutArgument in Workflow(WF 4)


            //Input Argument WF
            IDictionary<stringobject> inputs = new Dictionary<stringobject>
            {
                {"Person1"new Person{ Name="Tom", Age=26}}
            };
            
            //Output Argument
            IDictionary<string,object> outputs=WorkflowInvoker.Invoke(new Activity1(),inputs);
            Console.WriteLine(outputs["Accepted"].ToString());




Elmah Error Filtering(Ignore Some Exceptions)


Open the Global.asax file then write code;

void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs e)
        {
            if (e.Exception.GetBaseException() is FileNotFoundException || e.Exception.GetBaseException() is HttpException)
                e.Dismiss();
        }

Send Mail on Exception With Extensible Method


class Program
    {
        static void Main(string[] args)
        {
            try
            {
                throw new Exception("Expection");
            }
            catch (Exception ex)
            {
                ex.SendErrorEmail();
            }
        }
    }
    public static class MyExtension
    {
        public static void SendErrorEmail(this Exception ex)
        {
            //Write your send mail code
            //....
            smtpClient.Send(mailMessage);
        }
    }

Could not allocate space for object.


 In SqlServer right click on the database,select Database Properties.Then Go to Files section. Click the Autogrowth, select Unresticted File Growth.

How do you determine if your SQL Server Database is 32 or 64-bit?


select @@version

ASP.NET AutoMapper Application

Models;

public class Customer
    {
        public string Name{ getset;}
        public string Surname{ getset;}  
        public int ID{ getset;}
       
    }

 public class Person
    {
        public string FullName{ getset;}
        public int Age { getset; }
    }


Auto Mapper Class;
public class CustomerToPersonConverter:ITypeConverter<Customer,Person>
    {
 
        public Person Convert(ResolutionContext context)
        {
            Person person = new Person();
            Customer customer = context.SourceValue as Customer;
            person.Age = customer.ID + 15;
            person.FullName = customer.Name + " " + customer.Surname;
            return person;
        }
    }




In Page_Load;
 protected void Page_Load(object sender, EventArgs e)
        {
            Customer customer = new Customer()
            {
                ID=1,
                Name="Engin",
                Surname="Dotnet"
            };
            //Set The Map - #1
 Mapper.CreateMap<CustomerPerson>().ForMember(per => per.FullName, mus => mus.MapFrom(opt => opt.Name + " " + opt.Surname)).ForMember(per => per.Age, mus => mus.MapFrom(opt => opt.ID + 14));
 
            //Set The Map - #2
Mapper.CreateMap<CustomerPerson>().ConvertUsing<CustomerToPersonConverter>();
 
 
            //Set The Map - #3
 Mapper.CreateMap<CustomerPerson>().ConvertUsing(cus =>
   {
                    Person per = new Person();
                    per.Age = customer.ID + 15;
                    per.FullName = cus.Name + " " + cus.Surname;
                    return per;
     });
           
 
 
            ///Then Use
            Person person = Mapper.Map<CustomerPerson>(customer);
            Response.Write(person.Age + " " + person.FullName);
 
        }

Monday, October 10, 2011

Simple SQLite Application


protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            
            SQLiteConnection conn = new SQLiteConnection("Data Source=" + Server.MapPath("sqlitedb.db") + ";Version=3;");
            SQLiteDataAdapter adap = new SQLiteDataAdapter("select * from table", conn);
            conn.Open();
            DataTable dt = new DataTable();
            adap.Fill(dt);
            grd.DataSource = dt;
            grd.DataBind();
            conn.Close();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

Change WCF Service From Soap To Rest

In Service.svc change Factory Property;
Factory="System.ServiceModel.Activation.WebServiceHostFactory" 

Then;
Add WebGet Attribute WCF Method

Custom UserName-Password Validator in WCF Service

1-

public class MyCustomValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
//get from db or anywhere
            if (userName != "engin" && password != "dotnet")
            {
                throw new SecurityTokenException("Validation failed.");
            }
        }
    } 


2-In WebConfig
 <bindings>
      <basicHttpBinding>
        <binding name="basicBinding" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Basic">transport>
          security>
        binding>
      basicHttpBinding>
    bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="mexBeh">
          <serviceMetadata httpGetEnabled="true" />
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WcfServiceLibrary2.MyCustomValidator,WcfServiceLibrary2"/>
          serviceCredentials>
        behavior>
      serviceBehaviors>
    behaviors>
3-Finall write your code;
           WcfUserPassClient svc = new WcfUserPassClient();
            svc.ClientCredentials.UserName.UserName = "engin";
            svc.ClientCredentials.UserName.Password = "dotnet";
            string result = svc.DoWork();

With a single click install or unistall windows service


To Install;
Create a text file and named install.bat. Then type the following code

@ECHO OFF
 
set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727
set PATH=%PATH%;%DOTNETFX2%
 
echo Installing MyService...
echo ---------------------------------------------------
InstallUtil /i "ServicePath.exe"
echo ---------------------------------------------------
echo Done.
pause


To Unistall;

Create a text file and named uninstall.bat. Then type the following code

@ECHO OFF
 
set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727
set PATH=%PATH%;%DOTNETFX2%
 
echo Installing MyService...
echo ---------------------------------------------------
InstallUtil /u "ServicePath.exe"
echo ---------------------------------------------------
echo Done.
pause

ASP.NET Language Problem


 <globalization
           fileEncoding="iso-8859-9"
           requestEncoding="utf-8"
           responseEncoding="utf-8"
           culture="tr-TR"
           uiCulture="tr-TR"  />

Is Secure Connection In ASP.NET


            HttpContext.Current.Request.IsSecureConnection
or
            Request.ServerVariables["SERVER_PROTOCOL"];

Recently Executed Query


SELECT deqs.last_execution_time AS [Time], dest.TEXT AS [Query]
FROM sys.dm_exec_query_stats AS deqs CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle)
AS destORDER BY deqs.last_execution_time DESC


 More Information:SqlAuthority