0

ORACLE - UPDATE SEQUENCE VALUE USING LOOP

 DECLARE  l_counter NUMBER := 0;

t NUMBER:=0;

BEGIN

LOOP

    l_counter := l_counter + 1;

    IF l_counter > 32690 THEN

      EXIT;

    END IF;

    SELECT ISEQ$$_832661.nextval INTO t from dual;

  END LOOP;

END;

0

IIS - Cache Control must-revalidate"

Reference : Deploying to Microsoft Internet Information Server (IIS) | Gatsby (gatsbyjs.com)


<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <location path="static">
        <system.webServer>
            <httpProtocol>
                <customHeaders>
                    <remove name="cache-control" />
                    <add name="cache-control" value="public, max-age=31536000, immutable" />
                </customHeaders>
            </httpProtocol>
        </system.webServer>
    </location>
    <location path="page-data">
        <system.webServer>
            <httpProtocol>
                <customHeaders>
                    <remove name="cache-control" />
                    <add name="cache-control" value="public, max-age=0, must-revalidate" />
                </customHeaders>
            </httpProtocol>
        </system.webServer>
    </location>
    <system.webServer>
        <staticContent>
            <mimeMap fileExtension=".webmanifest" mimeType="application/manifest+json" />
        </staticContent>
        <rewrite>
            <outboundRules>
              <rule name="AdjustCacheForDontCacheFiles" preCondition="IsDontCacheFile" stopProcessing="true">
                <match serverVariable="RESPONSE_Cache-Control" pattern=".*" />
                <action type="Rewrite" value="public, max-age=0, must-revalidate" />
              </rule>
              <rule name="AdjustCacheForCachePermanentlyFiles" preCondition="IsCachePermanentlyFile" stopProcessing="true">
                <match serverVariable="RESPONSE_Cache-Control" pattern=".*" />
                <action type="Rewrite" value="public, max-age=31536000, immutable" />
              </rule>
              <preConditions>
                <preCondition name="IsDontCacheFile">
                  <add input="{REQUEST_FILENAME}" pattern="(.*\.html)|(sw\.js)|(app\-data\.json)|(page\-data\.json)" />
                </preCondition>
                <preCondition name="IsCachePermanentlyFile">
                  <add input="{REQUEST_FILENAME}" pattern="((.*\.js)|(.*\.css))$" />
                </preCondition>
              </preConditions>
            </outboundRules>
        </rewrite>
    </system.webServer>
</configuration>
0

SQL Server - Kill all Connected connection

Reference : https://stackoverflow.com/questions/7197574/script-to-kill-all-connections-to-a-database-more-than-restricted-user-rollback 

 For MS SQL Server 2012 and above


USE master;

DECLARE @kill varchar(8000); SET @kill = '';  
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';'  
FROM master..sysprocesses  
WHERE dbid = db_id('MyDB')

EXEC(@kill);



 For MS SQL Server 2000, 2005, 2008

 USE [master];
DECLARE @kill varchar(8000) = '';  
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), session_id) + ';'  
FROM sys.dm_exec_sessions
WHERE database_id  = db_id('MyDB')

EXEC(@kill);
0

SQL Server - find users connected to databases

Reference: https://jimsalasek.com/2019/01/09/sql-server-find-users-connected-to-databases/

SELECT @@ServerName AS server
 ,NAME AS DatabaseName
 ,COUNT(STATUS) AS number_of_connections
 ,GETDATE() AS Query_Run_Time
FROM sys.databases sd
LEFT JOIN sysprocesses sp ON sd.database_id = sp.dbid
WHERE NAME not in ('master','model','msdb','tempdb')
GROUP BY NAME

With actual usernames and machines that are connected


SELECT @@ServerName AS SERVER
 ,NAME
 ,login_time
 ,STATUS
 ,hostname
 ,program_name
 ,nt_username
 ,loginame
FROM sys.databases d
LEFT JOIN sysprocesses sp ON d.database_id = sp.dbid
WHERE  NAME not in ('master','model','msdb','tempdb')
 AND loginame IS NOT NULL order by 2



0

Automatically Replacing an Image on an HTML Page When it is Not Found

Reference : Automatically Replacing an Image on an HTML Page When it is Not Found - CodeProject


 <div>
    <img src="error.jpg" onerror="replaceImage(this, 'replacement.jpg');"
     title="This image is replaced on an error"/>
  </div>
 
  <script type="text/javascript">
    function replaceImage(image, replacementUrl){
      image.removeAttribute("onerror");
      image.src=replacementUrl;
    }
  </script>
0

Laravel get active session in minutes

select from_unixtime(`last_activity`) as lastdt from `sessions` WHERE from_unixtime(`last_activity`) >= NOW() - INTERVAL 15 MINUTE

ORDER BY last_activity DESC;


0

Datatable Search On Enter

Finally !!!!

Reference: jquery - datatables global search on keypress of enter key instead of any key keypress - Stack Overflow

Need to declare function on initComplete event. And use search function.

Datatable version 1.11.

$(function() {
    var  table = $('#DataTable1').DataTable({
            proccessing: true,
            searching: true,
            paging: true,
            serverSide: true,
            initComplete: function() {
                $('.dataTables_filter input').unbind();
                $('.dataTables_filter input').bind('keyup', function(e){
                    var code = e.keyCode || e.which;
                    if (code == 13) {
                        table.search(this.value).draw();
                    }
                });
            },
            ajax: {
            url: '@Url.Action("Paginacao")',
            type: 'POST'
        },
        language: {
            url: '/plugins/datatables/lang/Portuguese-Brasil.json'
        },
        columns:
        [
                { "data": "id", visible: false },
                { "data": "nome", "autoWidth": true },
                { "data": "cnpj", "autoWidth": true },
            {
                "render": function(data, type, full, meta) {
                    return '<a href=@Url.Action("Editar", "Usuario")?id='+full.id+'><b><i class=\"fa fa-edit bigfonts\"></i> Editar</b></a>';
                }
            }
        ]
    });

});
0

PHP - Access Object Attributes Dynamically

I want to access object attributes with child objects dynamically just by specifying the attribute in a string variable. 

$book->category->name


$attr="category->name";
$book=\App\Models\Book::find(2);
echo $book->$attr;

Result : null

Solution :

$attr="category->name";
$book=\App\Models\Book::find(2);
$parts=explode("->",$attr);
$h=$book;
foreach($parts as $p){
    $h=$h->$p;
}
echo $h;

Result : book category name



0

Using Docker Git Client

I've got a situation where the git client is not allowed to be installed on the production server (due to strict user policies) but I still want to use git without having to install the git client.

Finally, I found a solution using docker. (For this test I used Docker Desktop on Windows 11).

To clone a repository, just use the instructions below.


  docker run -ti  -v e:\repo\project1:/git alpine/git clone https://gitlab.com/test/project1.git ./

Need to map the volume (on my windows folder) to /git (in docker) and clone the repository to the current folder (./).

Then, git started cloning the repository.

To pull changes :


  docker run -ti --rm -v e:\repo\project1:/git alpine/git pull

0

ASP.NET Slug (MVC)

I want to use slug in ASP.NET MVC application. The URL should be something like this

localhost:58128/ABMB 

Here are the steps required to do so:

1. Defined the route (startup.cs)


 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

 routes.MapRoute(
   "Slug",
   "{slug}", 
       new { controller = "Home", action = "ScholarInfoDetails" } 
 );

2. Create SlugToIdAttribute.cs class

using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

/// 
/// Summary description for SlugToIdAttribute
/// 
public class SlugToIdAttribute : ActionFilterAttribute
{
    private ApplicationDbContext db = new ApplicationDbContext();

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var slug = filterContext.RouteData.Values["slug"] as string;
        if (slug != null)
        {
            var model=db.Banks.Where(x => x.Code == slug).First();
            if (model != null) {
                filterContext.ActionParameters["id"] = model.id.ToString();
            }            
        }
        base.OnActionExecuting(filterContext);
    }
}

3. Use in the controller. Add annotation [SlugToId]  

[AllowAnonymous]
[SlugToId]
public ActionResult ScholarInfoDetails(String id)
{
	var r = new ContentResult();
	r.Content = "Hello World " + id.ToString();
	return r;
}


Now the function can be access using slug. E.g http://localhost:58128/ABMB. Result will be something like this :
Hello World 2
0

SimpleSAML - SQLServer Connection

'sqlserver' => [
'sqlauth:SQL',
'dsn' => 'sqlsrv:Server=[server host / ip],1433;Database=[dbname]',
'username' => '[userid]',
'password' => '[password]',
'hash_column' => 'password',
'query' => 'SELECT users.uid, name AS cn, email AS mail,password FROM users WHERE users.email = :username',
'pepper' => '',
],
0

SimpleSAML and Active Directory configuration

References:

In config/authsources.php change example-ldap to the desired configuration

'example-ldap' =[
'ldap:LDAP',
hostname' = 'host.domain.com',
'enable_tls' = FALSE,
'debug' = TRUE,
'port' = 389,
'timeout' = 10,
'referrals' = FALSE,
'dnpattern' = 'sAMAccountName=%username%,ou=users,dc=company,dc=com',
'search.enable' = TRUE,
'search.base' = 'OU=users,DC=company,DC=com',
'search.attributes' = array('samAccountName'),
'search.username' = 'CN=yourname,OU=Users,DC=company,DC=Com',
'search.password' = ' ***** ',
'priv.read' = TRUE,
'priv.username' = '',
'priv.password' = '****'
]
0

Bootstrap 4 Datetime Picker With Custom Format Initialization

I had several date time picker with custom format (yyyy-MM-dd hh:mm:ss) in a page and don't want to initialize each element manually.

https://tempusdominus.github.io/bootstrap-4/
0

JQuery - textarea with character remaining using maxlength attribute

I want a simple solution to add the current text area with the remaining characters displayed without having to manually add counting elements.
0

GXT 3 - DateField date selection in a month

I want make the datefield to just allow selection in a month only.


DateField dateField = new DateField(new DateTimePropertyEditor(DateTimeFormat.getFormat("dd-MMM-yyyy")));

String sDate=session.getIps_year().toString() + "-" + session.getIps_month().toString() + "-01";        
Date mindate =Application.mysqlDateTimeFormat.parse(sDate);
dateField.setMinValue(mindate);    
dateField.getDatePicker().setMinDate(mindate);

Date maxdDate=CalendarUtil.copyDate(mindate);
CalendarUtil.addMonthsToDate(maxdDate, 1);
int days= CalendarUtil.getDaysBetween(mindate, maxdDate);
maxdDate=CalendarUtil.copyDate(mindate);
CalendarUtil.addDaysToDate(maxdDate, days-1);
dateField.setMaxValue(maxdDate);    
dateField.getDatePicker().setMaxDate(maxdDate);

0

GXT 3 Date Field Min & Max Date

I want to set min dan max date for datefield and want it disable the selection of dates out of specified range.

DateField dateField = new DateField(new DateTimePropertyEditor(DateTimeFormat.getFormat("dd-MMM-yyyy")));
dateField.getDatePicker().setMinDate(mindate);
dateField.getDatePicker().setMaxDate(maxdDate);
        
0

ASP.NET - Handling Form Submit on Enter Key Pressed

Source : http://weblog.kevinattard.com/2011/08/aspnet-disable-submit-form-on-enter-key.html

Actually I'm new to ASP.NET. This is my first attempt to develop a system that uses ASP.NET. It is not very difficult but there are some annoying things that need to be addressed. One of them is when the enter key is pressed, the form will be submitted, but logic is not triggered as it should be.

The steps are as follows:

1. In my case, I wrapped all the form content into an updatepanel.
2. Set the DefaultButton attribute of updatepanel to a button (it can be visible one, depends on your appplication)
3. Handle the logic.

Done. Tada.....

0

Changing the date and time on all files within a folder structure

Source : http://www.bradleymedia.org/touch-subfolders/

This is easily achieved by combining the touch command with the Linux find command using the dash exec action like :-

find * -exec touch {} \;
 
 
A better approach is to use the touch command with the dash t switch and specify 
an actual date and time. The example below will set all files to being modified at
ten a.m. on the 29th of Feb 2012.
 
find * -exec touch -t 201202291000 {} \; 
0

GXT Grid Anchor Cell

In previous post, I wrote about my solution to render image & link in grid cell.
This is the generic class to handle it.

import java.util.HashSet;
import java.util.Set;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.sencha.gxt.core.client.ValueProvider;

public class AnchorLinkCell<T> extends AbstractCell<T> {

    String imgURL = "";
    String styleClass = "";
    AsyncCallback<T> callback;
    ValueProvider<T, String> vp;

    public AnchorLinkCell(String imgURL, ValueProvider<T, String> vp, String styleClass, AsyncCallback<T> callback) {
        this.imgURL = imgURL;
        this.callback = callback;
        this.styleClass = styleClass;
        this.vp = vp;
    }

    @Override
    public void render(com.google.gwt.cell.client.Cell.Context context, T value, SafeHtmlBuilder sb) {
        sb.appendHtmlConstant("<div class=\"" + this.styleClass + "\" style='cursor: pointer'/>");
        if (imgURL != "") {
            sb.appendHtmlConstant("<img src='" + imgURL + "' style='cursor: pointer'/> ");
        }
        sb.append(SafeHtmlUtils.fromTrustedString(this.vp.getValue(value)));
        sb.appendHtmlConstant("</div>");
    }

    @Override
    public Set<String> getConsumedEvents() {
        Set<String> events = new HashSet<String>();
        events.add("click");
        return events;
    }

    @Override
    public void onBrowserEvent(com.google.gwt.cell.client.Cell.Context context, Element parent, T value, NativeEvent event, ValueUpdater<T> valueUpdater) {
        // TODO Auto-generated method stub
        super.onBrowserEvent(context, parent, value, event, valueUpdater);
        if (parent.getFirstChildElement().isOrHasChild(Element.as(event.getEventTarget()))) {
            this.callback.onSuccess(value);
        }
    }
}


Steps :

1. Declare column config with bean parameters and set the value as the identity of the bean.
ColumnConfig<PremiseBean, PremiseBean> prm_companyColumn = new ColumnConfig<PremiseBean, PremiseBean>(props.identity(), 150,"Company Name");
        

2. This can be done by adding an identity value provider in the property access interface.
IdentityValueProvider<PremiseBean> identity();


3. Declare the AnchorLinkCell and set the column cell.
AnchorLinkCell<PremiseBean> acLink=new AnchorLinkCell<PremiseBeanHelper.PremiseBean>("images/icons/add.png",props.prm_name(), "myLinkStyleNameinCSS", new AsyncCallback<PremiseBean>() {

    @Override
    public void onFailure(Throwable caught) {
        Application.handleException(caught);                
    }

    @Override
    public void onSuccess(PremiseBean result) {
        Info.display("AnchorLinkCall Test", result.getPk());                                
    }
});

prm_companyColumn.setCell(acLink);

4. Do the rest steps for the grid


0

GXT3 Grid Cell with clickable Image and hyperlink

Reference:
  1. http://stackoverflow.com/questions/18951897/gwt-imagecell-change-image-dynamically-in-a-datagrid-or-celltable
  2. http://stackoverflow.com/questions/4691801/how-can-i-render-a-clickabletextcell-as-an-anchor-in-a-gwt-celltable
  3. http://www.gwtproject.org/doc/latest/DevGuideUiCustomCells.html#cell-onBrowserEvent
I want to make the cell table in a grid to show icon and link in a column.
I tried to use anchor but unsuccessful. The cell grid only render text & image but not the event.
I found a solution using ImageCell.
Steps :

1. Set columnconfig
2. Declare ImageCell object
3. override render subroutine
4. Override getConsumedEvents - to expose click event
5.Override onBrowserEvent to handle the event

In this example, it's only handle the first child element, so I just group the image & link in a div.


ColumnConfig<PremiseBean, String> prm_nameColumn = new ColumnConfig<PremiseBean, String>(props.prm_name(), 150, "Name");
        
ImageCell ic = new ImageCell() {

    @Override
    public void render(com.google.gwt.cell.client.Cell.Context context, String value, SafeHtmlBuilder sb) {
        sb.appendHtmlConstant("<div class=\"myClickableCellTestStyle\" style='cursor: pointer'/>");
        sb.appendHtmlConstant("<img src='images/icons/add.png' style='cursor: pointer'/> ");
        sb.append(SafeHtmlUtils.fromTrustedString(value));
        sb.appendHtmlConstant("</div>");
    }

    @Override
    public Set<String> getConsumedEvents() {
        Set<String> events = new HashSet<String>();
        events.add("click");
        return events;
    }

    @Override
    public void onBrowserEvent(com.google.gwt.cell.client.Cell.Context context, Element parent, String value, NativeEvent event, ValueUpdater<String> valueUpdater) {
        super.onBrowserEvent(context, parent, value, event, valueUpdater);
        if (parent.getFirstChildElement().isOrHasChild(Element.as(event.getEventTarget()))) {
            Console.writeLine("OnEvent");
            Info.display("Test", value);
        }
    }
};
prm_nameColumn.setCell(ic);


add style to css.


.myClickableCellTestStyle{
    text-decoration:underline;
}
 
Copyright © peyotest