7 Şubat 2022 Pazartesi

ASP.NET MVC Autofac Implementation

 Öncelikle Autofac.Mvc5 Nuget Paketi projeye dahil edilmeli.

Daha sonra global.asax içinde Application_Start() metodunda aşağıdaki metod çağrılırsa Autofac da registration yapılır. Ayrıca MVC controllerlarda constructor da Dependency Injection için de AutofacDependencyResolver set edilmiş olur.

void AutofacRegisterAssemblyTypesFolder()
        {
            var dir = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
            var files = Directory.EnumerateFiles(dir);
            var types = files
                .Where(fileName => fileName.EndsWith("WebApplicationAutofac.dll") || fileName.EndsWith("MyDomain.dll"))
                .Select(filePath => Assembly.LoadFrom(filePath))
                .SelectMany(assembly => assembly.GetTypes())
                .Where(type => type.IsClass == true)
                .Where(type => type.FullName.StartsWith("WebApplicationAutofac.Domain") || type.FullName.StartsWith("MyDomain"));
                //.Where(type => type.GetInterfaces().Length > 0);
                
            var builder = new ContainerBuilder();
            var asm = Assembly.GetExecutingAssembly();
            builder.RegisterControllers(asm);
            //type registration
            //builder.RegisterType<Service>().As<IService>();
            //register interceptor
            builder.Register(c => new LogInterceptor());
            //oluşturulan instance register edilir. her talep edildiğinde aynı instance verilir. singleton çalışır
            builder.RegisterInstance(new InstanceDomain()).As<InstanceDomain>();
           //belirtilen assemblydeki registerlar
            foreach (var type in types)
            {
                var interfaces = type.GetInterfaces();
                if (interfaces.Length > 0)
                {
                    builder.RegisterType(type).As(interfaces[0])
                        .IfNotRegistered(type)
                        .EnableInterfaceInterceptors()
                        .InterceptedBy(typeof(LogInterceptor));
                }
                else
                {
                    builder.RegisterType(type).AsSelf()
                        .IfNotRegistered(type);
                }
            }
            IContainer container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }

23 Haziran 2021 Çarşamba

SQL Server DROP / CREATE all table foreign key

SET NOCOUNT ON

DECLARE @table TABLE(

RowId INT PRIMARY KEY IDENTITY(1, 1),

ForeignKeyConstraintName NVARCHAR(200),

ForeignKeyConstraintTableSchema NVARCHAR(200),

ForeignKeyConstraintTableName NVARCHAR(200),

ForeignKeyConstraintColumnName NVARCHAR(200),

PrimaryKeyConstraintName NVARCHAR(200),

PrimaryKeyConstraintTableSchema NVARCHAR(200),

PrimaryKeyConstraintTableName NVARCHAR(200),

PrimaryKeyConstraintColumnName NVARCHAR(200)

)

INSERT INTO @table(ForeignKeyConstraintName, ForeignKeyConstraintTableSchema, ForeignKeyConstraintTableName, ForeignKeyConstraintColumnName)

SELECT

U.CONSTRAINT_NAME,

U.TABLE_SCHEMA,

U.TABLE_NAME,

U.COLUMN_NAME

FROM

INFORMATION_SCHEMA.KEY_COLUMN_USAGE U

INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C

ON U.CONSTRAINT_NAME = C.CONSTRAINT_NAME

WHERE

C.CONSTRAINT_TYPE = 'FOREIGN KEY'

UPDATE @table SET

PrimaryKeyConstraintName = UNIQUE_CONSTRAINT_NAME

FROM

@table T

INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R

ON T.ForeignKeyConstraintName = R.CONSTRAINT_NAME

UPDATE @table SET

PrimaryKeyConstraintTableSchema = TABLE_SCHEMA,

PrimaryKeyConstraintTableName = TABLE_NAME

FROM @table T

INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C

ON T.PrimaryKeyConstraintName = C.CONSTRAINT_NAME

UPDATE @table SET

PrimaryKeyConstraintColumnName = COLUMN_NAME

FROM @table T

INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U

ON T.PrimaryKeyConstraintName = U.CONSTRAINT_NAME

--SELECT * FROM @table

--DROP CONSTRAINT:

SELECT

'

ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + ']

DROP CONSTRAINT ' + ForeignKeyConstraintName + '

 

GO'

FROM

@table

--ADD CONSTRAINT:

SELECT

'

ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + ']

ADD CONSTRAINT ' + ForeignKeyConstraintName + ' FOREIGN KEY(' + ForeignKeyConstraintColumnName + ') REFERENCES [' + PrimaryKeyConstraintTableSchema + '].[' + PrimaryKeyConstraintTableName + '](' + PrimaryKeyConstraintColumnName + ')

 

GO'

FROM

@table

GO

17 Haziran 2021 Perşembe

Windows Servisi Oluşturma ve Silme

 sc.exe create DenemeServis1 start=auto binpath=D:\_temp\Debug1\RopEnterprise.WinService.exe displayname=DenemeServis1

sc.exe delete DenemeServis1

18 Mart 2019 Pazartesi

ASP.NET MVC ActionFilterAttribute, IActionFilter Intercept Requests

    public class CustomActionFilter : ActionFilterAttribute, IActionFilter
    {
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            Stopwatch tmr = new Stopwatch();
            tmr.Start();
            filterContext.HttpContext.Items["tmr"] = tmr;
            Debug.WriteLine(JsonConvert.SerializeObject(filterContext.ActionParameters));
        }

        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
        {
            Stopwatch tmr = (Stopwatch)filterContext.HttpContext.Items["tmr"];
            Debug.WriteLine(tmr.ElapsedMilliseconds);
        }
    }

        [CustomActionFilter]
        public ActionResult Index(string p1, string p2)
        {
            return Content(DateTime.Now.ToString());
        }

23 Ocak 2019 Çarşamba

MS SQL Server Date StartOfDay EndOfDay

CREATE FUNCTION [dbo].[fnDate_EndOfDay]
(
@date datetime
)
RETURNS datetime
AS
BEGIN
return CONVERT(DATETIME, CONVERT(varchar(11), @date, 111 ) + ' 23:59:59', 111)
END

CREATE FUNCTION [dbo].[fnDate_StartOfDay]
(
@date datetime
)
RETURNS datetime
AS
BEGIN
return CONVERT(DATETIME, CONVERT(varchar(11), @date, 111 ) + ' 00:00:00', 111)
END


print dbo.fnDate_StartOfDay(getdate())
print dbo.fnDate_EndOfDay(getdate())


Jan 24 2019 12:00AM
Jan 24 2019 11:59PM

14 Ocak 2019 Pazartesi

WebClient UploadString POST Object as JSON

            string apiUrl = "http://localhost:14101/Print/MutfakAdisyonYazdir";

            var req = new MutfakAdisyonYazdir_RequestDTO();
            req.TokenGuid = Guid.NewGuid().ToString();
            req.AdisyonSiparisIdler = new List<long>() { 123, 234, 345, 456 };

            string inputJson = JsonHelper.Serialize(req);
            WebClient client = new WebClient();
            client.Headers["Content-type"] = "application/json";
            client.Encoding = Encoding.UTF8;
            string json = client.UploadString(apiUrl, inputJson);

            var resp = JsonHelper.Deserialize<BaseResponseDTO>(json);

8 Ocak 2019 Salı

SQL Server Reorganize All Indexes in Database

declare @tableName nvarchar(500)
declare @indexName nvarchar(500)
declare @indexType nvarchar(55)
declare @percentFragment decimal(11,2)

declare FragmentedTableList cursor for
 SELECT OBJECT_NAME(ind.OBJECT_ID) AS TableName,
   ind.name AS IndexName, indexstats.index_type_desc AS IndexType,
   indexstats.avg_fragmentation_in_percent
 FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) indexstats
   INNER JOIN sys.indexes ind ON ind.object_id = indexstats.object_id
        AND ind.index_id = indexstats.index_id
  WHERE
-- indexstats.avg_fragmentation_in_percent , e.g. >30, you can specify any number in percent
   indexstats.avg_fragmentation_in_percent > 5
  AND ind.Name is not null
  ORDER BY indexstats.avg_fragmentation_in_percent DESC

    OPEN FragmentedTableList
    FETCH NEXT FROM FragmentedTableList 
    INTO @tableName, @indexName, @indexType, @percentFragment

    WHILE @@FETCH_STATUS = 0
    BEGIN
      print 'Processing ' + @indexName + ' on table ' + @tableName + ' which is ' + cast(@percentFragment as nvarchar(50)) + ' fragmented'
     
      if(@percentFragment<= 30)
      BEGIN
            EXEC( 'ALTER INDEX [' +  @indexName + '] ON ' + @tableName + ' REBUILD; ')
       print 'Finished reorganizing ' + @indexName + ' on table ' + @tableName
      END
      ELSE
      BEGIN
         EXEC( 'ALTER INDEX [' +  @indexName + '] ON ' + @tableName + ' REORGANIZE;')
        print 'Finished rebuilding ' + @indexName + 'on table ' + @tableName
      END 
      FETCH NEXT FROM FragmentedTableList 
        INTO @tableName, @indexName, @indexType, @percentFragment
    END
    CLOSE FragmentedTableList
    DEALLOCATE FragmentedTableList

12 Temmuz 2018 Perşembe

SSH Login Without Password Using ssh-keygen & ssh-copy-id

1. create public key
[red.red-pc] ➤ ssh-keygen

WARNING:

You should not store anything in MobaXterm HOME directoy (/home/mobaxterm): with your current settings, this folder is not "persistent", so it will be cleared at each MobaXterm restart.

If you want to set a "persistent" HOME directory which will not be cleared at each MobaXterm startup, go to MobaXterm settings window and choose a folder in which to store MobaXterm home files.

Generating public/private rsa key pair.
Enter file in which to save the key (/home/mobaxterm/.ssh/id_rsa):
/home/mobaxterm/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/mobaxterm/.ssh/id_rsa.
Your public key has been saved in /home/mobaxterm/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:InGPnZ7IvfhE/ejPBFOOsdoWGGVitbmKm7T/4M2RsD8 red@red-pc

2. copy the public key to remote host
[red.red-pc] ➤ ssh-copy-id -i id_rsa.pub 10.123.105.119
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
red@10.123.105.119's password:


Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '10.123.105.119'"
and check to make sure that only the key(s) you wanted were added.

3. login to remote host whitout password
[red.red-pc] ➤ ssh root@10.123.105.119
Last login: Thu Jul 12 16:26:06 2018 from 10.123.105.101

11 Haziran 2018 Pazartesi

Python Get Script Path

print(os.path.dirname(os.path.realpath(__file__)))
or
print(os.path.dirname(os.path.realpath(sys.argv[0])))

31 Mart 2018 Cumartesi

SQL Server Refresh All View

SET NOCOUNT ON
DECLARE @SQL varchar(max) = ''
SELECT @SQL = @SQL + 'print ''Refreshing --> ' + name + '''
EXEC sp_refreshview ' + name + ';
'
  FROM sysobjects
  WHERE type = 'V' --< condition to select all views, may vary by your standards
--SELECT @SQL
EXEC(@SQL)