问:
Response.Redirect Fails But then Works on Refresh IIS Express VS2013
I have an ASP.NET project in Visual Studio 2013, running locally in IIExpress (Version 8.08418.0) for testing.

The main page (adminDefault.aspx) redirects user to Login.aspx to authenticate (which is done silently based on userID that was passed to adminDefault.aspx as a url variable). The login page sends it back to adminDefault.aspx upon successful authentication. Default then loads data into a Gridview.

The whole process takes about 15 seconds.

When I run this from Visual Studio 2013, I get an error "This page can't be displayed" in about 4 seconds. But if I manually hit refresh, after working for a bit, everything comes in fine.

In my code, suspecting a timeout, I implicitly set this long enough to run through everything:

```<code> if (!this.IsPostBack)
            {

                Session.Timeout = 120;  // seconds before timeout
                try
                {
                    // OnUser should have been set from Login.asp. If it is null, send to Login
                    MembershipUser onUser = Membership.GetUser();
                    if (onUser == null)
                    {
                        Response.Redirect("/login.aspx", true);
                    }
                    else
                    {
                        String currentUserName = Membership.GetUser().UserName;
                        userRoles = Roles.GetRolesForUser(Membership.GetUser().UserName);
                    }
                }
</code>```

Even if the Session.Timeout is being ignored, the default is 20 Seconds, so I would expect it to work anyway.

So:
1) Why is the first run through failing?
2) Is there a way I can prevent it? Failing that can I catch the page not found, and refresh automatically?

EDIT: This has something to do with the trip to Login.aspx and back. If I remove Response.Redirect("/login.aspx", true);
Then this works as expected. The problem is, I need the Login.aspx for validation. Anyone have any thoughts as to why the trip to Login and back is not working... and then does upon refresh?

When I try to run this in Chrome, I don't get as far. Chrome shows me this:

Hitting the here just cycles for a moment and comes back to the screen.

The Developer Tool on IE are not helpful (at least that i can see) in this case. When I run my project in the debugger, it launches a new IE session. Before I can turn on developer tools and press "Play" to record events, the session has given me "Cannot display the page" error. Of course I can hit "play" in the tools and then refresh, but of course everything runs then without error. The refresh makes everything run right. I need to discover why it fails before then.

EDIT: This is the Login.aspx and Web.Security Code. I didn't write it, but it looks boilerplate:

```<code>  protected void Page_Load(object sender, EventArgs e)
    {
            string userName = "";
            bool authenticated = FormsAuthentication.Authenticate(ref userName);
            if (authenticated)
                {
                    FormsAuthentication.RedirectFromLoginPage(userName, false);
                }
     }
</code>```

And the Authentication code looks like this:

```<code>        /// <summary>
    /// Validates a user based on the  session id found in the ReturnURL against credentials stored in the ASP.NET membership.
    /// </summary>
    /// <param name="userName">The user name.</param>
    /// <returns>true if the user name and password are valid; otherwise, false.</returns>
    public static bool Authenticate(ref string userName)
    {
        bool Authenticated = Authenticate(ref userName, GetSessionId());
        return Authenticated;
    }

    /// <summary>
    /// Redirects an authenticated user back to the originally requested URL or the default URL using the specified cookie path for the forms-authentication cookie.
    /// </summary>
    /// <param name="userName">The authenticated user name. </param>
    /// <param name="createPersistentCookie">true to create a durable cookie (one that is saved across browser sessions); otherwise, false. </param>
    /// <param name="strCookiePath">The cookie path for the forms-authentication ticket. </param>
    public static void RedirectFromLoginPage(string userName, bool createPersistentCookie, string strCookiePath)
    {
        System.Web.Security.FormsAuthentication.SetAuthCookie(userName, false, strCookiePath);

        // Redirect back to request page.
        HttpContext.Current.Response.Redirect(GetRedirectUrl());
    }
</code>```

答:
I think in your initial if statment you are assuming everyone is either logged in or not logged in.But users that are not logged in and people who visit that can also be anonymous (?). What you want to do is secure this admin.Default page and only allow authorized users. Currently your 2 conditions are send back the user to the login.aspx page (that they are currently on) if a user = null or get a role.
Authentication is about knowing who the user is while authorization is all about access to resources .You want only authorized users to access that resource.

I would put the admin.Default.aspx,admin.Default.cs and admin.Default.designer.cs in their own folder called AdminSecure. Then after adding them inside that folder right click and add a Web.config file. In that Web.config what you need to do is deny anonymous users. So they automatically get redirected when they try and access that AdminDefault page.

//denies non logged in users ? == anonymous

```<code><xml version="1.0"?>
<configuration>
    <system.web>
<authorization>
  <deny users="?"/>
</authorization>
    </system.web>
</configuration>

//this can allow particular users
<allow users="User1@mail.com"/>

//deny everyone but one user:
<allow users="User1@mail.com"/>
<deny users="*"/>
</code>```

comment out your current code hope this helps.

Body:
I have an ASP.NET project in Visual Studio 2013, running locally in IIExpress (Version 8.08418.0) for testing.

The main page (adminDefault.aspx) redirects user to Login.aspx to authenticate (which is done silently based on userID that was passed to adminDefault.aspx as a url variable). The login page sends it back to adminDefault.aspx upon successful authentication. Default then loads data into a Gridview.

The whole process takes about 15 seconds.

When I run this from Visual Studio 2013, I get an error "This page can't be displayed" in about 4 seconds. But if I manually hit refresh, after working for a bit, everything comes in fine.

In my code, suspecting a timeout, I implicitly set this long enough to run through everything:

 if (!this.IsPostBack)
            {

                Session.Timeout = 120;  // seconds before timeout
                try
                {
                    // OnUser should have been set from Login.asp. If it is null, send to Login
                    MembershipUser onUser = Membership.GetUser();
                    if (onUser == null)
                    {
                        Response.Redirect("/login.aspx", true);
                    }
                    else
                    {
                        String currentUserName = Membership.GetUser().UserName;
                        userRoles = Roles.GetRolesForUser(Membership.GetUser().UserName);
                    }
                }

Even if the Session.Timeout is being ignored, the default is 20 Seconds, so I would expect it to work anyway.

So:
1) Why is the first run through failing?
2) Is there a way I can prevent it? Failing that can I catch the page not found, and refresh automatically?

EDIT: This has something to do with the trip to Login.aspx and back. If I remove Response.Redirect("/login.aspx", true);
Then this works as expected. The problem is, I need the Login.aspx for validation. Anyone have any thoughts as to why the trip to Login and back is not working... and then does upon refresh?

When I try to run this in Chrome, I don't get as far. Chrome shows me this:

Hitting the here just cycles for a moment and comes back to the screen.

The Developer Tool on IE are not helpful (at least that i can see) in this case. When I run my project in the debugger, it launches a new IE session. Before I can turn on developer tools and press "Play" to record events, the session has given me "Cannot display the page" error. Of course I can hit "play" in the tools and then refresh, but of course everything runs then without error. The refresh makes everything run right. I need to discover why it fails before then.

EDIT: This is the Login.aspx and Web.Security Code. I didn't write it, but it looks boilerplate:

  protected void Page_Load(object sender, EventArgs e)
    {
            string userName = "";
            bool authenticated = FormsAuthentication.Authenticate(ref userName);
            if (authenticated)
                {
                    FormsAuthentication.RedirectFromLoginPage(userName, false);
                }
     }

And the Authentication code looks like this:

        ///
    /// Validates a user based on the  session id found in the ReturnURL against credentials stored in the ASP.NET membership.
    ///
    /// <param name="userName">The user name.</param>
    /// <returns>true if the user name and password are valid; otherwise, false.</returns>
    public static bool Authenticate(ref string userName)
    {
        bool Authenticated = Authenticate(ref userName, GetSessionId());
        return Authenticated;
    }

    ///
    /// Redirects an authenticated user back to the originally requested URL or the default URL using the specified cookie path for the forms-authentication cookie.
    ///
    /// <param name="userName">The authenticated user name. </param>
    /// <param name="createPersistentCookie">true to create a durable cookie (one that is saved across browser sessions); otherwise, false. </param>
    /// <param name="strCookiePath">The cookie path for the forms-authentication ticket. </param>
    public static void RedirectFromLoginPage(string userName, bool createPersistentCookie, string strCookiePath)
    {
        System.Web.Security.FormsAuthentication.SetAuthCookie(userName, false, strCookiePath);

        // Redirect back to request page.
        HttpContext.Current.Response.Redirect(GetRedirectUrl());
    }

Body:
I think in your initial if statment you are assuming everyone is either logged in or not logged in.But users that are not logged in and people who visit that can also be anonymous (?). What you want to do is secure this admin.Default page and only allow authorized users. Currently your 2 conditions are send back the user to the login.aspx page (that they are currently on) if a user = null or get a role.
Authentication is about knowing who the user is while authorization is all about access to resources .You want only authorized users to access that resource.

I would put the admin.Default.aspx,admin.Default.cs and admin.Default.designer.cs in their own folder called AdminSecure. Then after adding them inside that folder right click and add a Web.config file. In that Web.config what you need to do is deny anonymous users. So they automatically get redirected when they try and access that AdminDefault page.

//denies non logged in users ? == anonymous

<xml version="1.0"?>
<configuration>
    <system.web>
<authorization>
  <deny users="?"/>
</authorization>
    </system.web>
</configuration>

//this can allow particular users
<allow users="User1@mail.com"/>

//deny everyone but one user:
<allow users="User1@mail.com"/>
<deny users="*"/>

comment out your current code hope this helps.


来源: stackexchange

问:
Put arraylist in hashmap with key as one of the columns
I have a resultSet which is having multiple rows. I want to make a hashmap. But while storing the arrayList and making key as one of the columns, for each key all the rows are stored in arrayList.
That means for each key all the rows are stored rather than the exact rows for that key.

HashMap> map = new HashMap>();
       Pojo pojo = null;
       PreparedStatement ps = null;
       ResultSet rs = null;
       ArrayList list = null;

```<code>   try {
       ps = DatabaseManager.prepareStatement(query);
       ps.setInt(1, number);
       rs = ps.executeQuery();
       while(rs.next()){

         pojo = new Pojo();
         pojo.setId(rs.getInt("ID"));
         pojo.setDate(rs.getDate("DATE"));
         pojo.setTotal(rs.getDouble("TOTAL"));

         list.add(pojo); map.put(rs.getInt("ID"), list);
       }
       rs.close();
</code>```

So for all the keys the size of list is 15. While it should be like
  ID      Rows
  1A        3
  2A        4
  3C        2
  4W        6

So how the code should be to get the desired result?

答:
You can try something like this,

```<code>while(rs.next()){
    // Check if map contains list
    if (map.contains(rs.getInt("ID"))
        list = map.get(rs.getInt("ID"));
    else
        list = new ArrayList<Pojo>();

    pojo = new Pojo();
    pojo.setId(rs.getInt("ID"));
    pojo.setDate(rs.getDate("DATE"));
    pojo.setTotal(rs.getDouble("TOTAL"));

    list.add(pojo);
    map.put(rs.getInt("ID"), list);
}
</code>```

Hope it works.

ContentLicense: CC BY-SA 3.0

Body:
I have a resultSet which is having multiple rows. I want to make a hashmap. But while storing the arrayList and making key as one of the columns, for each key all the rows are stored in arrayList.
That means for each key all the rows are stored rather than the exact rows for that key.

HashMap> map = new HashMap>();
       Pojo pojo = null;
       PreparedStatement ps = null;
       ResultSet rs = null;
       ArrayList list = null;

   try {
       ps = DatabaseManager.prepareStatement(query);
       ps.setInt(1, number);
       rs = ps.executeQuery();
       while(rs.next()){

         pojo = new Pojo();
         pojo.setId(rs.getInt("ID"));
         pojo.setDate(rs.getDate("DATE"));
         pojo.setTotal(rs.getDouble("TOTAL"));

         list.add(pojo); map.put(rs.getInt("ID"), list);
       }
       rs.close();

So for all the keys the size of list is 15. While it should be like
  ID      Rows
  1A        3
  2A        4
  3C        2
  4W        6

So how the code should be to get the desired result?

Body:
You can try something like this,

while(rs.next()){
    // Check if map contains list
    if (map.contains(rs.getInt("ID"))
        list = map.get(rs.getInt("ID"));
    else
        list = new ArrayList<Pojo>();

    pojo = new Pojo();
    pojo.setId(rs.getInt("ID"));
    pojo.setDate(rs.getDate("DATE"));
    pojo.setTotal(rs.getDouble("TOTAL"));

    list.add(pojo);
    map.put(rs.getInt("ID"), list);
}

Hope it works.


问:
server side & end-user web application security and validation methods
I was wondering what security method everyone uses to secure a web application at bank grade if possible.

from the best of my knowledge here are the methods/technologies that i know of.

```<code>Front - End-user Section
-------------------------
SSL (128 bit encryption)
htaccess (protection against bots and using mod-rewrite to hide parameter calls)
input field cleaning
session cleaning before use
PDO access to mysql ( although oracle is better yet expensive)
not being on a shared hosting account.
using a cisco based firewall (not very familiar with these)
restricting what can be uploaded (if the site requires an upload)
blocking off directory index access with htaccess
not storing credit card information locally
encrypting user passwords with sha1 or encryption with salt
(never could figure these out)

not using hidden input fields
turn off global variables
turn off error displays
using another file extension displayed to the user rather than php , aspx, etc.
blocking ping/requests for server/apache information and version.

backend access
-------------------
not having its access being something like /admin (if you know what i mean)
"all of the above listed for end-user"
verifying if the user who logs in exists as an admin
</code>```

rather than using mysql_real_escape_string or htmlentities to clean input fields
then there is filter_input() which doesnt work that good. it kind of messes up the cleaning.
so what do you guys recommend. i know some of you might be thinking this might be a bit too much but if your working on a web application that was to be hit by over 50k users where ecommerce based transactions would occur. what would you do?

thanks

ps: this is what i have in my htaccess to protect against non-friendly bots and restricting access to important files.

```<code>#=============================================================================#
#          Deny access to hidden files
#=============================================================================#
<FilesMatch "\.(htaccess|log|sh)$">
 Order Allow,Deny
 Deny from all
</FilesMatch>

#=============================================================================#
#          Deny access to evil bots / security
#=============================================================================#

RewriteBase /
RewriteCond %{HTTP_USER_AGENT} ^JetCar.* [NC]
RewriteCond %{HTTP_USER_AGENT} ^FlashGet.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Teleport.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^NetAnts.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^WebZIP.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Offline.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^GetRight.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Go!Zilla.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^GoZilla.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^WebReaper.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^ia_archiver.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^wget.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^HTTrack.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^WebStripper.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^WebCapture.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Scooter-W3.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^WebCopier.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^FlashGe.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Webdupe.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^NetAnts.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Pockey.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^DiscoPump.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^InternetNinja.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^BlackWidow [OR]
RewriteCond %{HTTP_USER_AGENT} ^Bot\ mailto:craftbot@yahoo.com [OR]
RewriteCond %{HTTP_USER_AGENT} ^ChinaClaw [OR]
RewriteCond %{HTTP_USER_AGENT} ^Custo [OR]
RewriteCond %{HTTP_USER_AGENT} ^DISCo [OR]
RewriteCond %{HTTP_USER_AGENT} ^Download\ Demon [OR]
RewriteCond %{HTTP_USER_AGENT} ^eCatch [OR]
RewriteCond %{HTTP_USER_AGENT} ^EirGrabber [OR]
RewriteCond %{HTTP_USER_AGENT} ^EmailSiphon [OR]
RewriteCond %{HTTP_USER_AGENT} ^EmailWolf [OR]
RewriteCond %{HTTP_USER_AGENT} ^Express\ WebPictures [OR]
RewriteCond %{HTTP_USER_AGENT} ^ExtractorPro [OR]
RewriteCond %{HTTP_USER_AGENT} ^EyeNetIE [OR]
RewriteCond %{HTTP_USER_AGENT} ^FlashGet [OR]
RewriteCond %{HTTP_USER_AGENT} ^GetRight [OR]
RewriteCond %{HTTP_USER_AGENT} ^GetWeb! [OR]
RewriteCond %{HTTP_USER_AGENT} ^Go!Zilla [OR]
RewriteCond %{HTTP_USER_AGENT} ^Go-Ahead-Got-It [OR]
RewriteCond %{HTTP_USER_AGENT} ^GrabNet [OR]
RewriteCond %{HTTP_USER_AGENT} ^Grafula [OR]
RewriteCond %{HTTP_USER_AGENT} ^HMView [OR]
RewriteCond %{HTTP_USER_AGENT} ^HTTrack [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Image\ Stripper [OR]
RewriteCond %{HTTP_USER_AGENT} ^Image\ Sucker [OR]
RewriteCond %{HTTP_USER_AGENT} ^Indy\ Library [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^InterGET [OR]
RewriteCond %{HTTP_USER_AGENT} ^Internet\ Ninja [OR]
RewriteCond %{HTTP_USER_AGENT} ^JetCar [OR]
RewriteCond %{HTTP_USER_AGENT} ^JOC\ Web\ Spider [OR]
RewriteCond %{HTTP_USER_AGENT} ^larbin [OR]
RewriteCond %{HTTP_USER_AGENT} ^LeechFTP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Mass\ Downloader [OR]
RewriteCond %{HTTP_USER_AGENT} ^MIDown\ tool [OR]
RewriteCond %{HTTP_USER_AGENT} ^Mister\ PiX [OR]
RewriteCond %{HTTP_USER_AGENT} ^Navroad [OR]
RewriteCond %{HTTP_USER_AGENT} ^NearSite [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetAnts [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Net\ Vampire [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetZIP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Octopus [OR]
RewriteCond %{HTTP_USER_AGENT} ^Offline\ Explorer [OR]
RewriteCond %{HTTP_USER_AGENT} ^Offline\ Navigator [OR]
RewriteCond %{HTTP_USER_AGENT} ^PageGrabber [OR]
RewriteCond %{HTTP_USER_AGENT} ^Papa\ Foto [OR]
RewriteCond %{HTTP_USER_AGENT} ^pavuk [OR]
RewriteCond %{HTTP_USER_AGENT} ^pcBrowser [OR]
RewriteCond %{HTTP_USER_AGENT} ^RealDownload [OR]
RewriteCond %{HTTP_USER_AGENT} ^ReGet [OR]
RewriteCond %{HTTP_USER_AGENT} ^SiteSnagger [OR]
RewriteCond %{HTTP_USER_AGENT} ^SmartDownload [OR]
RewriteCond %{HTTP_USER_AGENT} ^SuperBot [OR]
RewriteCond %{HTTP_USER_AGENT} ^SuperHTTP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Surfbot [OR]
RewriteCond %{HTTP_USER_AGENT} ^tAkeOut [OR]
RewriteCond %{HTTP_USER_AGENT} ^Teleport\ Pro [OR]
RewriteCond %{HTTP_USER_AGENT} ^VoidEYE [OR]
RewriteCond %{HTTP_USER_AGENT} ^Web\ Image\ Collector [OR]
RewriteCond %{HTTP_USER_AGENT} ^Web\ Sucker [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebAuto [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebCopier [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebFetch [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebGo\ IS [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebLeacher [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebReaper [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebSauger [OR]
RewriteCond %{HTTP_USER_AGENT} ^Website\ eXtractor [OR]
RewriteCond %{HTTP_USER_AGENT} ^Website\ Quester [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebStripper [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebWhacker [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebZIP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Wget [OR]
RewriteCond %{HTTP_USER_AGENT} ^Widow [OR]
RewriteCond %{HTTP_USER_AGENT} ^WWWOFFLE [OR]
RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^GoZilla.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^WebCapture.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Webdupe.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Pockey.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^DiscoPump.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^InternetSeer.com.* [NC,OR]
RewriteCond %{HTTP_REFERER} ^http://www.hostitcheap.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.bravespider.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.bigweblist.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.weblinkvalidator.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://traffixer.com* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.youradultpaysite.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.paysiteprofits.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.hotlivewebcams.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.paysiteprofits.com/* [OR]
RewriteCond %{REQUEST_URI} FormMail.*
RewriteCond %{HTTP_REFERER} ^www.addresses.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.business-socket.com/* [OR]
RewriteCond %{HTTP_REFERER} ^www.datashaping.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://cheapweb.biz/* [OR]
RewriteCond %{HTTP_REFERER} ^http://traffixer.com* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.hostitcheap.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.weblinkvalidator.com/* [OR]
RewriteCond %{REQUEST_URI} FormMail.*
RewriteRule .* - [F,L]
</code>```

答:
Go through every script and really use good input sanitation. If the data should be numeral, then make sure it only accepts numbers and so on. This is where most of the middlelevel bugs are found.

Dont have patterns in your htaccess for files you want to block. Instead block everything and only allow a specific set of files that you know are going to be used.

Make application (or even different parts of application) run with specially designed users of the database, with limited access. If a part of an application just displays information from a table, the db user it uses to connect to the database should only be able to see that particular table, and should only be able to read that database, not modify it. Report all the strange database permission errors to a special file and check regularly.

Be very careful around eval(), obvisouly never just run anything that comes from the outside of the script, better yet don't use eval() at all.

Carefully set permissions on the user that the server runs with. It should only be able to write to the diretories it needs to, and files in those directories should never be allowed to execute.

And most importantly, never start to think that your application is safe. Nothing is safe. New bugs and even types of bugs are coming out all the time, keep an eye out for them. You can for example subscribe to some security bulletin, and check with new bugs and exploits that come out, and then try to think if the same kind of exploit could be used on some part of your application.

ContentLicense: CC BY-SA 2.5

Body:
I was wondering what security method everyone uses to secure a web application at bank grade if possible.

from the best of my knowledge here are the methods/technologies that i know of.

Front - End-user Section
-------------------------
SSL (128 bit encryption)
htaccess (protection against bots and using mod-rewrite to hide parameter calls)
input field cleaning
session cleaning before use
PDO access to mysql ( although oracle is better yet expensive)
not being on a shared hosting account.
using a cisco based firewall (not very familiar with these)
restricting what can be uploaded (if the site requires an upload)
blocking off directory index access with htaccess
not storing credit card information locally
encrypting user passwords with sha1 or encryption with salt
(never could figure these out)

not using hidden input fields
turn off global variables
turn off error displays
using another file extension displayed to the user rather than php , aspx, etc.
blocking ping/requests for server/apache information and version.

backend access
-------------------
not having its access being something like /admin (if you know what i mean)
"all of the above listed for end-user"
verifying if the user who logs in exists as an admin

rather than using mysql_real_escape_string or htmlentities to clean input fields
then there is filter_input() which doesnt work that good. it kind of messes up the cleaning.
so what do you guys recommend. i know some of you might be thinking this might be a bit too much but if your working on a web application that was to be hit by over 50k users where ecommerce based transactions would occur. what would you do?

thanks

ps: this is what i have in my htaccess to protect against non-friendly bots and restricting access to important files.

#=============================================================================#
#          Deny access to hidden files
#=============================================================================#
<FilesMatch "\.(htaccess|log|sh)$">
 Order Allow,Deny
 Deny from all
</FilesMatch>

#=============================================================================#
#          Deny access to evil bots / security
#=============================================================================#

RewriteBase /
RewriteCond %{HTTP_USER_AGENT} ^JetCar.* [NC]
RewriteCond %{HTTP_USER_AGENT} ^FlashGet.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Teleport.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^NetAnts.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^WebZIP.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Offline.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^GetRight.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Go!Zilla.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^GoZilla.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^WebReaper.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^ia_archiver.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^wget.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^HTTrack.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^WebStripper.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^WebCapture.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Scooter-W3.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^WebCopier.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^FlashGe.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Webdupe.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^NetAnts.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Pockey.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^DiscoPump.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^InternetNinja.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^BlackWidow [OR]
RewriteCond %{HTTP_USER_AGENT} ^Bot\ mailto:craftbot@yahoo.com [OR]
RewriteCond %{HTTP_USER_AGENT} ^ChinaClaw [OR]
RewriteCond %{HTTP_USER_AGENT} ^Custo [OR]
RewriteCond %{HTTP_USER_AGENT} ^DISCo [OR]
RewriteCond %{HTTP_USER_AGENT} ^Download\ Demon [OR]
RewriteCond %{HTTP_USER_AGENT} ^eCatch [OR]
RewriteCond %{HTTP_USER_AGENT} ^EirGrabber [OR]
RewriteCond %{HTTP_USER_AGENT} ^EmailSiphon [OR]
RewriteCond %{HTTP_USER_AGENT} ^EmailWolf [OR]
RewriteCond %{HTTP_USER_AGENT} ^Express\ WebPictures [OR]
RewriteCond %{HTTP_USER_AGENT} ^ExtractorPro [OR]
RewriteCond %{HTTP_USER_AGENT} ^EyeNetIE [OR]
RewriteCond %{HTTP_USER_AGENT} ^FlashGet [OR]
RewriteCond %{HTTP_USER_AGENT} ^GetRight [OR]
RewriteCond %{HTTP_USER_AGENT} ^GetWeb! [OR]
RewriteCond %{HTTP_USER_AGENT} ^Go!Zilla [OR]
RewriteCond %{HTTP_USER_AGENT} ^Go-Ahead-Got-It [OR]
RewriteCond %{HTTP_USER_AGENT} ^GrabNet [OR]
RewriteCond %{HTTP_USER_AGENT} ^Grafula [OR]
RewriteCond %{HTTP_USER_AGENT} ^HMView [OR]
RewriteCond %{HTTP_USER_AGENT} ^HTTrack [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Image\ Stripper [OR]
RewriteCond %{HTTP_USER_AGENT} ^Image\ Sucker [OR]
RewriteCond %{HTTP_USER_AGENT} ^Indy\ Library [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^InterGET [OR]
RewriteCond %{HTTP_USER_AGENT} ^Internet\ Ninja [OR]
RewriteCond %{HTTP_USER_AGENT} ^JetCar [OR]
RewriteCond %{HTTP_USER_AGENT} ^JOC\ Web\ Spider [OR]
RewriteCond %{HTTP_USER_AGENT} ^larbin [OR]
RewriteCond %{HTTP_USER_AGENT} ^LeechFTP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Mass\ Downloader [OR]
RewriteCond %{HTTP_USER_AGENT} ^MIDown\ tool [OR]
RewriteCond %{HTTP_USER_AGENT} ^Mister\ PiX [OR]
RewriteCond %{HTTP_USER_AGENT} ^Navroad [OR]
RewriteCond %{HTTP_USER_AGENT} ^NearSite [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetAnts [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^Net\ Vampire [OR]
RewriteCond %{HTTP_USER_AGENT} ^NetZIP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Octopus [OR]
RewriteCond %{HTTP_USER_AGENT} ^Offline\ Explorer [OR]
RewriteCond %{HTTP_USER_AGENT} ^Offline\ Navigator [OR]
RewriteCond %{HTTP_USER_AGENT} ^PageGrabber [OR]
RewriteCond %{HTTP_USER_AGENT} ^Papa\ Foto [OR]
RewriteCond %{HTTP_USER_AGENT} ^pavuk [OR]
RewriteCond %{HTTP_USER_AGENT} ^pcBrowser [OR]
RewriteCond %{HTTP_USER_AGENT} ^RealDownload [OR]
RewriteCond %{HTTP_USER_AGENT} ^ReGet [OR]
RewriteCond %{HTTP_USER_AGENT} ^SiteSnagger [OR]
RewriteCond %{HTTP_USER_AGENT} ^SmartDownload [OR]
RewriteCond %{HTTP_USER_AGENT} ^SuperBot [OR]
RewriteCond %{HTTP_USER_AGENT} ^SuperHTTP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Surfbot [OR]
RewriteCond %{HTTP_USER_AGENT} ^tAkeOut [OR]
RewriteCond %{HTTP_USER_AGENT} ^Teleport\ Pro [OR]
RewriteCond %{HTTP_USER_AGENT} ^VoidEYE [OR]
RewriteCond %{HTTP_USER_AGENT} ^Web\ Image\ Collector [OR]
RewriteCond %{HTTP_USER_AGENT} ^Web\ Sucker [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebAuto [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebCopier [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebFetch [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebGo\ IS [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebLeacher [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebReaper [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebSauger [OR]
RewriteCond %{HTTP_USER_AGENT} ^Website\ eXtractor [OR]
RewriteCond %{HTTP_USER_AGENT} ^Website\ Quester [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebStripper [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebWhacker [OR]
RewriteCond %{HTTP_USER_AGENT} ^WebZIP [OR]
RewriteCond %{HTTP_USER_AGENT} ^Wget [OR]
RewriteCond %{HTTP_USER_AGENT} ^Widow [OR]
RewriteCond %{HTTP_USER_AGENT} ^WWWOFFLE [OR]
RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR]
RewriteCond %{HTTP_USER_AGENT} ^GoZilla.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^WebCapture.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Webdupe.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^Pockey.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^DiscoPump.* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^InternetSeer.com.* [NC,OR]
RewriteCond %{HTTP_REFERER} ^http://www.hostitcheap.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.bravespider.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.bigweblist.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.weblinkvalidator.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://traffixer.com* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.youradultpaysite.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.paysiteprofits.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.hotlivewebcams.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.paysiteprofits.com/* [OR]
RewriteCond %{REQUEST_URI} FormMail.*
RewriteCond %{HTTP_REFERER} ^www.addresses.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.business-socket.com/* [OR]
RewriteCond %{HTTP_REFERER} ^www.datashaping.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://cheapweb.biz/* [OR]
RewriteCond %{HTTP_REFERER} ^http://traffixer.com* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.hostitcheap.com/* [OR]
RewriteCond %{HTTP_REFERER} ^http://www.weblinkvalidator.com/* [OR]
RewriteCond %{REQUEST_URI} FormMail.*
RewriteRule .* - [F,L]


问:
Field is being sliced when using solr pivot
I have the following query:

```<code>/search?facet.pivot=host&facet.pivot=name&facet=on&indent=on&q=&rows=10&start=0&wt=json
</code>```

and this is the response header

```<code>"responseHeader":{
    "zkConnected":true,
    "status":0,
    "QTime":420,
    "params":{
      "q":"",
      "facet.pivot":["host",
        "name"],
      "indent":"on",
      "start":"0",
      "rows":"10",
      "facet":"on",
      "wt":"json",
      "_":"1512394263979"}}
</code>```

The host part is always a domain stackoverflow.com or google.com,  While the name is a full name something like Stack Exchange Inc or Google Inc. so using this query the results is like this:

```<code>"response":{"numFound":2,"start":0,"maxScore":56.923157,"docs":[
      {
        "host":"google.com",
        "name":"Google Inc."},
      {
        "url":"stackoverflow.com",
        "name":"Stack Exchange Inc."},
      ]
 },
 "facet_counts":{
"facet_queries":{},
"facet_fields":{},
"facet_ranges":{},
"facet_intervals":{},
"facet_heatmaps":{},
"facet_pivot":{
  "host":[{
      "field":"host",
      "value":"google.com",
      "count":1},
    {
      "field":"host",
      "value":"stackoverflow.com",
      "count":1}]
 },
 "facet_pivot":{
  "name":[{
      "field":"name",
      "value":"Inc.",
      "count":2
    {
      "field":"name",
      "value":"Google",
      "count":1},
    {
      "field":"name",
      "value":"Stack",
      "count":1},
    {
      "field":"name",
      "value":"Exchange",
      "count":1}]
 },
 ....
</code>```

The question is how can i match the whole name? so the pivot will be

```<code>"facet_pivot":{
      "name":[{
          "field":"name",
          "value":"Google Inc.",
          "count":1},
        {
          "field":"name",
          "value":"Stack Exchange Inc.",
          "count":1}]
     },
</code>```

答:
Found the issue. name field type is text which is being tokenized so it will be sliced -by spaces- into multi-words. The solution would be to copy the name field to another field with type 'string' and then facet.pivot=name_str would solve the issue

More explanation in this answer : https://stackoverflow.com/a/17915897/2724879

Body:
I have the following query:

/search?facet.pivot=host&facet.pivot=name&facet=on&indent=on&q=&rows=10&start=0&wt=json

and this is the response header

"responseHeader":{
    "zkConnected":true,
    "status":0,
    "QTime":420,
    "params":{
      "q":"",
      "facet.pivot":["host",
        "name"],
      "indent":"on",
      "start":"0",
      "rows":"10",
      "facet":"on",
      "wt":"json",
      "_":"1512394263979"}}

The host part is always a domain stackoverflow.com or google.com,  While the name is a full name something like Stack Exchange Inc or Google Inc. so using this query the results is like this:

"response":{"numFound":2,"start":0,"maxScore":56.923157,"docs":[
      {
        "host":"google.com",
        "name":"Google Inc."},
      {
        "url":"stackoverflow.com",
        "name":"Stack Exchange Inc."},
      ]
 },
 "facet_counts":{
"facet_queries":{},
"facet_fields":{},
"facet_ranges":{},
"facet_intervals":{},
"facet_heatmaps":{},
"facet_pivot":{
  "host":[{
      "field":"host",
      "value":"google.com",
      "count":1},
    {
      "field":"host",
      "value":"stackoverflow.com",
      "count":1}]
 },
 "facet_pivot":{
  "name":[{
      "field":"name",
      "value":"Inc.",
      "count":2
    {
      "field":"name",
      "value":"Google",
      "count":1},
    {
      "field":"name",
      "value":"Stack",
      "count":1},
    {
      "field":"name",
      "value":"Exchange",
      "count":1}]
 },
 ....

The question is how can i match the whole name? so the pivot will be

"facet_pivot":{
      "name":[{
          "field":"name",
          "value":"Google Inc.",
          "count":1},
        {
          "field":"name",
          "value":"Stack Exchange Inc.",
          "count":1}]
     },


问:
Oracle 12c Forms & Reports setup_fmw_12.2.1.3.0_fr_win64.exe installation error: self-extraction to C:\...... .tmp failed
While installing Oracle 12c Forms & Reports: setup_fmw_12.2.1.3.0_fr_win64.exe file, got installation error: self-extraction to C:...... .tmp failed

How can I successfully install the Oracle Forms Reports?
I already have installed the weblogic infrastructure.

答: It is solved now. The solution is do not unzip setup_fmw_12.2.1.3.0_fr_win64-2.zip file and keep it together with the first exe file, setup_fmw_12.2.1.3.0_fr_win64.exe. Run the exe in admin mode.</p>


问:
How to manage third-party asemblies in a (nuget-) consistent way?
or: How to automate nuspec/nupkgs creation?

TL; DR;

Our project teams need to manage many third party-libraries for which no nuget-packages exist, along with (of course) many nuget-based dependencies. We´d like to manage these dependencies in the most nuget-consistent way, but handcrafting nuspecs kindof sucks. How can we automate the creation of nuget-packages for our third-party dependencies?

Background

The project teams in our company are using certain third-party libraries in many of our projects, for which no public available nuget-packages exist, like DevExpress DevExtreme controls libraries, or similar.

We often are having difficulties setting up Continous Integration (CI) / - Deployment (CD) pipelines for these projects, as our build-agents (a "co-located-on-premise" Team Foundation Server (TFS) atm) often lack the required assemblies / components in order to successfully build these projects. This often leeds to unsuccessfull builds when setting up new build-agents (e.g. when moving to a newer TFS version) or when setting up new projects. This further results in tideous installation of component-suits, most of the time even with a load of different versions of the respective libraries and "reference-fiddling" in order to support building (legacy) applications.

This problem was traditionally solved most of the time by manually managing dependencies on code-repository level in the past, e.g. by checking in dependencies in a "dependencies"-folder in the code-repository root - but this approach is

bloating the repo with every version-update by hundreds of megabytes at least, from day one

tideous in figuring out the dependency-hierarchy and identifying the needed assemblies

error-prone when it comes to re-reference assemblies from e.g. the GAC to said dependency-directory

a style breaker in sense of "modern" dependency management "the nuget way"

I understand that licensing-concerns keep library-vendors from publishing their components via public nuget feeds in the first place, but this stylistic inconsistency in managing references totally sucks.
(The rise of nuget and package managers in general say enough about the "traditional approach" of dependency management)

And even if such vendors eventually decide to support a "native" packages for referenceing their stuff in the future, there still is the question about legacy-apps which e.g. use older versions of the libs.

Of course there is the option to setting up our dev-machines as build agents. But this is no solution for us, as our projects are rather long-living in sense of support and our dev-machines are kind of fragile in comparison (these easyly get wiped at least once a year, if not more often here and there; Our projects often need to build even after longer inactivity periods after e.g. five (5), or even ten (10) years).

I think many of you guys and gals out their are facing similar issues, expecially in larger orgs.

One way to address this is to maually craft nuget-packages for this libraries. This limits the tideous work of making sense of the assembliey-hierarchie to a "one timer" (at least per library-version) and "magically" takes care of the assembly-"re-referencing", but is also error prone (at least at authoring-time of the respective nuspec) and a really (really) painful task, especially when it comes to newer library-versions, which often come with more dependencies)

How do you folks address these kind of issues?
Isn´t there something out there to automate this?

答:
Yes, there definitely is a way.

Introducing TeGun

from the TeGun github-repository:

TeGun (NuGet reversed) is a simple, yet handy cross-platform(.netcore) commandline-utility for creating nuget packages (nupkg) from a bunch of ordinary, unpackaged assemblies. The main goal is to provide a fast tooling experience when dealing with third-party assemblies that do not come packaged via e.g. Nuget.org.

Just point (dotnet-)tegun, to a directory containing the third-party assemblies.
TeGun will scan the assemblies, analyze their dependencies and create **.nuspecs* for them, respecting internal dependencies to prevent packages with "duplicate/redundant" assemblies in it.

You can influence naming- and versioning-schemes of packages and even pre-define bundle-packages via wildcard-patterns, to bundle e.g. Theme-Assemblies for UI-Components.

This helps at least in the initial creation of * .nuspecs The produced **.nuspecs* can either be further tweeked to suit your needs or be used out-of-the-box to produce consumable packages via NuGet.exe-tooling.
From that on, you are free to decide over which channel you consume them (like a local Network-Share or Nuget-Feed), and creating packages e.g. based on updated libraries is a breeze.

After TeGun´s initial release I created a total of 1200 packages weighin almost 1.5 GB for a large component-suite , which spans over 5 major versions, in under 30 Minutes (and from this timeframe, TeGun itself was doing most of the work). And this was just for one vendor of one library.

I even managed to create packages that upgdrade from on major-version to another major-version via nuget-package-explorer, and another variant that "locks" the major-version, but respects vendor-updates from package explorer (just because I could, and because some of our projects are kind of precautios regarding major version upgrades of e.G. UI component suits)

This way, the packages provides a kind of "fast-ring" and "slow-ring" in the sense of library-updates.

Sample

This sample is also available on GitHub

Let´s assume we have an app that does some MS Office-automation. Hence it requires certain assemblies from the Office-SDKs. We identify a bunch of available assemblies and copy them to c:\temp\officeSDK. The contents of the directory might look like his:

Microsoft.Office.Interop.OneNote.dll

Microsoft.Office.Interop.Outlook.dll

Microsoft.Office.Interop.OutlookViewCtl.dll

Microsoft.Office.Interop.PowerPoint.dll

Microsoft.Office.Interop.Publisher.dll

...

In order to invoke TeGun, we utilize the dotnet cli extension point as described here. So let´s create a TeGun-enabled project

```<code>dotnet new tegun
dotnet restore
</code>```

This will create a project with a DotNetCliToolReference to the actual TeGun-Executable, which will be downloaded upon restore

TeGun uses a config file for most of it´s settings atm (see #1). Let´s initialize a new config with:

```<code>dotnet tegun init office
</code>```

This wil create an initial office.config.json pointing to assemblies in the current directory.

Open the config to tweak the package-creation to your needs:

```<code>{
  "assemblies": {
    "sources": [
      "."  //scan the local directory for assemblies
    ],
    "excludePatterns": [
      "System.*" //exclude matching assemblies
    ],
    "bundles": [
      {
        "searchPattern": "Microsoft.Office.*", //Bundle all matching assemblies
        "packageId": "OfficeBundle.Sample",    //into a package
        "packageVersion": "1.2.3.4"            //with this version
      }
    ],
    "substitutions": [
      {
        "replace": "Interop",
        "with": "xxx"
      },
    ]
  },
  //general nuspec-creation settings
  "package": {
    "authors": "earloc",
    "owners": "earloc",
    "tags": [ //additional tags
      "tags",
      "go",
      "here"
    ],
    "targetframeworks": [
      "net45"
    ],
    "versionFormat": "{Major}.{Minor}.{Build}.{Revision}", //Use full version number from scanned assembly as package version
    "title": {
      "prefix": "earloc.", //prefix package names
      "suffix": ""
    },
    "nuspecTemplate": null
  }
}
</code>```

If we now invoke the command:

```<code>dotnet tegun nuspec office
</code>```

TeGun will create nuspec-files according to the above settings in the subfolder office/nuspecs:

OfficeBundle.Sample.1.2.3.nuspec

earloc.Microsoft.Office.xxx.OneNote.14.0.0.nuspec

earloc.Microsoft.Office.xxx.Outlook.14.0.0.nuspec

earloc.Microsoft.Office.xxx.OutlookViewCtl.14.0.0.nuspec

earloc.Microsoft.Office.xxx.PowerPoint.14.0.0.nuspec

earloc.Microsoft.Office.xxx.Publisher.14.0.0.nuspec

...

These nuspecs can now be further tweaked to your needs and be used to produce packages, e.g. with a simple batch file in the office subfolder:

```<code>set nuget=nuget.exe
for /R nuspecs %%f in (*.nuspec) do (
    %nuget% pack %%f  -OutputDirectory packages
)
</code>```

will produce the following packages at office/packages:

OfficeBundle.Sample.1.2.3.nupkg

earloc.Microsoft.Office.xxx.OneNote.14.0.0.nupkg

earloc.Microsoft.Office.xxx.Outlook.14.0.0.nupkg

earloc.Microsoft.Office.xxx.OutlookViewCtl.14.0.0.nupkg

earloc.Microsoft.Office.xxx.PowerPoint.14.0.0.nupkg

earloc.Microsoft.Office.xxx.Publisher.14.0.0.nupkg

...

Limitations

TeGun does not support automatic inclusion of satelite assemblies atm, but it´s a feature I am working on when I find the time (contributions accepted ;) ).

Body:
Yes, there definitely is a way.

Introducing TeGun

from the TeGun github-repository:

TeGun (NuGet reversed) is a simple, yet handy cross-platform(.netcore) commandline-utility for creating nuget packages (nupkg) from a bunch of ordinary, unpackaged assemblies. The main goal is to provide a fast tooling experience when dealing with third-party assemblies that do not come packaged via e.g. Nuget.org.

Just point (dotnet-)tegun, to a directory containing the third-party assemblies.
TeGun will scan the assemblies, analyze their dependencies and create **.nuspecs* for them, respecting internal dependencies to prevent packages with "duplicate/redundant" assemblies in it.

You can influence naming- and versioning-schemes of packages and even pre-define bundle-packages via wildcard-patterns, to bundle e.g. Theme-Assemblies for UI-Components.

This helps at least in the initial creation of * .nuspecs The produced **.nuspecs* can either be further tweeked to suit your needs or be used out-of-the-box to produce consumable packages via NuGet.exe-tooling.
From that on, you are free to decide over which channel you consume them (like a local Network-Share or Nuget-Feed), and creating packages e.g. based on updated libraries is a breeze.

After TeGun´s initial release I created a total of 1200 packages weighin almost 1.5 GB for a large component-suite , which spans over 5 major versions, in under 30 Minutes (and from this timeframe, TeGun itself was doing most of the work). And this was just for one vendor of one library.

I even managed to create packages that upgdrade from on major-version to another major-version via nuget-package-explorer, and another variant that "locks" the major-version, but respects vendor-updates from package explorer (just because I could, and because some of our projects are kind of precautios regarding major version upgrades of e.G. UI component suits)

This way, the packages provides a kind of "fast-ring" and "slow-ring" in the sense of library-updates.

Sample

This sample is also available on GitHub

Let´s assume we have an app that does some MS Office-automation. Hence it requires certain assemblies from the Office-SDKs. We identify a bunch of available assemblies and copy them to c:\temp\officeSDK. The contents of the directory might look like his:

Microsoft.Office.Interop.OneNote.dll

Microsoft.Office.Interop.Outlook.dll

Microsoft.Office.Interop.OutlookViewCtl.dll

Microsoft.Office.Interop.PowerPoint.dll

Microsoft.Office.Interop.Publisher.dll

...

In order to invoke TeGun, we utilize the dotnet cli extension point as described here. So let´s create a TeGun-enabled project

dotnet new tegun
dotnet restore

This will create a project with a DotNetCliToolReference to the actual TeGun-Executable, which will be downloaded upon restore

TeGun uses a config file for most of it´s settings atm (see #1). Let´s initialize a new config with:

dotnet tegun init office

This wil create an initial office.config.json pointing to assemblies in the current directory.

Open the config to tweak the package-creation to your needs:

{
  "assemblies": {
    "sources": [
      "."  //scan the local directory for assemblies
    ],
    "excludePatterns": [
      "System.*" //exclude matching assemblies
    ],
    "bundles": [
      {
        "searchPattern": "Microsoft.Office.*", //Bundle all matching assemblies
        "packageId": "OfficeBundle.Sample",    //into a package
        "packageVersion": "1.2.3.4"            //with this version
      }
    ],
    "substitutions": [
      {
        "replace": "Interop",
        "with": "xxx"
      },
    ]
  },
  //general nuspec-creation settings
  "package": {
    "authors": "earloc",
    "owners": "earloc",
    "tags": [ //additional tags
      "tags",
      "go",
      "here"
    ],
    "targetframeworks": [
      "net45"
    ],
    "versionFormat": "{Major}.{Minor}.{Build}.{Revision}", //Use full version number from scanned assembly as package version
    "title": {
      "prefix": "earloc.", //prefix package names
      "suffix": ""
    },
    "nuspecTemplate": null
  }
}

If we now invoke the command:

dotnet tegun nuspec office

TeGun will create nuspec-files according to the above settings in the subfolder office/nuspecs:

OfficeBundle.Sample.1.2.3.nuspec

earloc.Microsoft.Office.xxx.OneNote.14.0.0.nuspec

earloc.Microsoft.Office.xxx.Outlook.14.0.0.nuspec

earloc.Microsoft.Office.xxx.OutlookViewCtl.14.0.0.nuspec

earloc.Microsoft.Office.xxx.PowerPoint.14.0.0.nuspec

earloc.Microsoft.Office.xxx.Publisher.14.0.0.nuspec

...

These nuspecs can now be further tweaked to your needs and be used to produce packages, e.g. with a simple batch file in the office subfolder:

set nuget=nuget.exe
for /R nuspecs %%f in (*.nuspec) do (
    %nuget% pack %%f  -OutputDirectory packages
)

will produce the following packages at office/packages:

OfficeBundle.Sample.1.2.3.nupkg

earloc.Microsoft.Office.xxx.OneNote.14.0.0.nupkg

earloc.Microsoft.Office.xxx.Outlook.14.0.0.nupkg

earloc.Microsoft.Office.xxx.OutlookViewCtl.14.0.0.nupkg

earloc.Microsoft.Office.xxx.PowerPoint.14.0.0.nupkg

earloc.Microsoft.Office.xxx.Publisher.14.0.0.nupkg

...

Limitations

TeGun does not support automatic inclusion of satelite assemblies atm, but it´s a feature I am working on when I find the time (contributions accepted ;) ).


问:
Wordpress local site switching to live URL
I am trying to install an existing wordpress site on my local machine
Ive set up database and site, but the issue Im having is when I hit the site on my local machine at url mysite.local it resolves to the live site mysite.com

What IVe done:

changed the URL of site_url and home in the options table in db
turned off all plugins
searched and replaced any hardcoded url in code (there were many!) and replaced with site_url()

Ive even noticed that when I call the site and it resolves to live URL the site_url and home values in options table are getting re-written with the live URL

Im not at all familiar with WP so Im wondering if Im missing something obvious or if anyone has run into similar issues

when the page is called IVe noticed that it sets a 302 permanently moved header

any ideas?

答:
Make sure that all occurrences in the database are replaced. You can use the below SQL</p>

```<code>UPDATE wp_options SET option_value = replace(option_value, 'http://oldsite', 'http://newsite') WHERE option_name = 'home' OR option_name = 'siteurl';

UPDATE wp_posts SET guid = replace(guid, 'http://oldsite', 'http://newsite');

UPDATE wp_posts SET post_content = replace(post_content, 'http://oldsite', 'http://newsite');

UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://oldsite', 'http://newsite');
</code>```

Body:
Make sure that all occurrences in the database are replaced. You can use the below SQL

UPDATE wp_options SET option_value = replace(option_value, 'http://oldsite', 'http://newsite') WHERE option_name = 'home' OR option_name = 'siteurl';

UPDATE wp_posts SET guid = replace(guid, 'http://oldsite', 'http://newsite');

UPDATE wp_posts SET post_content = replace(post_content, 'http://oldsite', 'http://newsite');

UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://oldsite', 'http://newsite');


问:
Automatically copy a file from one GitHub repository to another via Codehip
I have two repositories: S1, S2

I would like to automatically push a file from S1 to S2 if it is changed or created.

For example:

I push translation.en.json to /translations/translation.en.json in S1.
translation.en.json should automatically pushed to /dashboard/translation.en.json in S2.

When I push something to master branch in S1 then the codeship build will be run.

I want to write a script in codeship steps which can do this automatic push.

I tried something like this:

```<code>#!/bin/bash
set -e
mkdir -p _translations/dashboard/
cd _translations
git fetch --unshallow || true
git fetch origin "+refs/heads/*:refs/remotes/origin/*"
git push git@github.com:company/translations.git "${CI_COMMIT_ID}:master"
</code>```

答:
We have a script based deployment for pushing to a different git repository available at https://github.com/codeship/scripts/blob/master/deployments/git_push.sh

You can add that to your deployment pipeline by adding a Script Deployment by setting the required environment variables and adding the curl command, e.g.

```<code>export REMOTE_REPOSITORY="git@github.com:company/s2.git"
export REMOTE_BRANCH="master"
\curl -sSL https://raw.githubusercontent.com/codeship/scripts/master/deployments/git_push.sh | bash -s
</code>```

You will also need to make sure that the Codeship projects SSH key (available via the project settings) is allowed to push to the second repository. See https://documentation.codeship.com/general/projects/access-to-other-repositories-fails-during-build/ for how to configure this.

However, this will push the complete contents for S1 to the other repository. If you only want to push a specific file (or a set of files) I'd recommend cloning the second repository, copying the files over and then committing and pushing. A sample script could look like this:

```<code>cd "${HOME}"
git clone git@github.com:company/s2.git
# "${HOME}/clone" is the default checkout path on Codeship
cp ./clone/translation.en.json ./s2/
cd ./s2
git commit -a "Automatic commit, based on "company/s1@${CI_COMMIT_ID}"
git push origin master
</code>```

Please note, that this script is not tested and definitely needs to be adapted to your specific needs. The note regarding authentication and access to the second repository applies to this use case as well.

Body:
I have two repositories: S1, S2

I would like to automatically push a file from S1 to S2 if it is changed or created.

For example:

I push translation.en.json to /translations/translation.en.json in S1.
translation.en.json should automatically pushed to /dashboard/translation.en.json in S2.

When I push something to master branch in S1 then the codeship build will be run.

I want to write a script in codeship steps which can do this automatic push.

I tried something like this:

#!/bin/bash
set -e
mkdir -p _translations/dashboard/
cd _translations
git fetch --unshallow || true
git fetch origin "+refs/heads/*:refs/remotes/origin/*"
git push git@github.com:company/translations.git "${CI_COMMIT_ID}:master"

Body:
We have a script based deployment for pushing to a different git repository available at https://github.com/codeship/scripts/blob/master/deployments/git_push.sh

You can add that to your deployment pipeline by adding a Script Deployment by setting the required environment variables and adding the curl command, e.g.

export REMOTE_REPOSITORY="git@github.com:company/s2.git"
export REMOTE_BRANCH="master"
\curl -sSL https://raw.githubusercontent.com/codeship/scripts/master/deployments/git_push.sh | bash -s

You will also need to make sure that the Codeship projects SSH key (available via the project settings) is allowed to push to the second repository. See https://documentation.codeship.com/general/projects/access-to-other-repositories-fails-during-build/ for how to configure this.

However, this will push the complete contents for S1 to the other repository. If you only want to push a specific file (or a set of files) I'd recommend cloning the second repository, copying the files over and then committing and pushing. A sample script could look like this:

cd "${HOME}"
git clone git@github.com:company/s2.git
# "${HOME}/clone" is the default checkout path on Codeship
cp ./clone/translation.en.json ./s2/
cd ./s2
git commit -a "Automatic commit, based on "company/s1@${CI_COMMIT_ID}"
git push origin master

Please note, that this script is not tested and definitely needs to be adapted to your specific needs. The note regarding authentication and access to the second repository applies to this use case as well.


问:
How many SHA256 hashes can a modern computer compute?
I want to know the mathematical time required for cracking hashes based off different sets of characters.

For example, using only 7 letter, US-ASCII alphabetic characters we know that there are 267 possible sequences that could be used. Knowing how many of these could be generated by a computer each minute would give me an idea of how long it would take to generate all possible hashes and crack a certain 7 character hash (birthday attacks aside).

For example, taking the number above, if a modern quad core could generate 1 million hashes each minute it would take 8031810176 / 1000000 / 60 = 133.86 hours to find all possible hashes in that range.

Also, how does the new Sandy Bridge Intel chips with native AES play into this?

答:
I wrote this test in C using the OpenSSL SHA256 implementation.

```<code>#include <stdio.h>
#include <string.h>
#include "openssl/sha.h"

// http://stackoverflow.com/questions/4764608/generate-all-strings-under-length-n-in-c/4764686#4764686
int inc(char *str) {
    if (!str[0]) return 0;

    if (str[0] == 'z') {
        str[0] = 'a';
        return inc(str + sizeof(char));
    }

    str[0]++;
    return 1;
}

unsigned char buffer[65];
char* hashstring(char *str, int len) {
    char hash[SHA256_DIGEST_LENGTH]; // the openssl hash
    SHA256_CTX sha256;
    int i; // counter

    SHA256_Init(&sha256);
    SHA256_Update(&sha256, str, len);
    SHA256_Final(hash, &sha256);

    for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
        sprintf(buffer + (i * 2), "%02x", hash[i]); // convert openssl hash to mortal human string
    }

    return buffer;
}

int main(int argc, char *argv[]) {
    int N = 4; // max length string
    char str[N+1]; // the string holder
    int i; // counter

    unsigned int tot = 0; // number of hashes calculated

    for (i = 0; i < N; i++) str[i] = 'a';
    str[N] = 0;

    do {
        hashstring(str, N);
        tot++;
    } while(inc(str));

    printf("%d\n", tot);
}
</code>```

Compile:

```<code>gcc -lcrypto -O3 -o test test.c
</code>```

And results (I know, I'm not very creative with computernames):

```<code>nightcracker@nightcracker-pc:~/c/sha256$ time ./test
11881376

real    3m2.431s
user    3m2.335s
sys 0m0.008s
</code>```

So that's 11881376 / 182.4 = 65139 hashes per second. Then it's 26^7/101821/3600 = 34 hours to compute all the hashes. Please note, all of this was done on a Q6600 quad-core CPU in a single-threaded application and excluded writing the hashes to file.

EDIT

Woops, I was calculating all the hashes of strings with N characters and below. Corrected and data updated.

Body:
I wrote this test in C using the OpenSSL SHA256 implementation.

#include <stdio.h>
#include <string.h>
#include "openssl/sha.h"

// http://stackoverflow.com/questions/4764608/generate-all-strings-under-length-n-in-c/4764686#4764686
int inc(char *str) {
    if (!str[0]) return 0;

    if (str[0] == 'z') {
        str[0] = 'a';
        return inc(str + sizeof(char));
    }

    str[0]++;
    return 1;
}

unsigned char buffer[65];
char* hashstring(char *str, int len) {
    char hash[SHA256_DIGEST_LENGTH]; // the openssl hash
    SHA256_CTX sha256;
    int i; // counter

    SHA256_Init(&sha256);
    SHA256_Update(&sha256, str, len);
    SHA256_Final(hash, &sha256);

    for (i = 0; i < SHA256_DIGEST_LENGTH; i++) {
        sprintf(buffer + (i * 2), "%02x", hash[i]); // convert openssl hash to mortal human string
    }

    return buffer;
}

int main(int argc, char *argv[]) {
    int N = 4; // max length string
    char str[N+1]; // the string holder
    int i; // counter

    unsigned int tot = 0; // number of hashes calculated

    for (i = 0; i < N; i++) str[i] = 'a';
    str[N] = 0;

    do {
        hashstring(str, N);
        tot++;
    } while(inc(str));

    printf("%d\n", tot);
}

Compile:

gcc -lcrypto -O3 -o test test.c

And results (I know, I'm not very creative with computernames):

nightcracker@nightcracker-pc:~/c/sha256$ time ./test
11881376

real    3m2.431s
user    3m2.335s
sys 0m0.008s

So that's 11881376 / 182.4 = 65139 hashes per second. Then it's 26^7/101821/3600 = 34 hours to compute all the hashes. Please note, all of this was done on a Q6600 quad-core CPU in a single-threaded application and excluded writing the hashes to file.

EDIT

Woops, I was calculating all the hashes of strings with N characters and below. Corrected and data updated.


问:
Resize url image to equal parts
I need help with an html / css
in my application to upload the photo in the profile, the user needs to pass the url of the image, I save this url in the database and put this url in my HTML $ {user.fotoProfile}

however, when the image comes with equal proportions, eg. 150x150, 650x650, 960x960 whatever. the setup works and fills my field without distortion.

but when the image does not have equal proportions, the image field is distorted.

Can someone help me?

HTML

```<code>                     <div class="user-img">
                        <a href='profile'><img src="<c:url value="${user.fotoProfile}" />" alt="user-img" class="img-circle img-thumbnail img-responsive"></a>
                        <div class="user-status offline"><i class="zmdi zmdi-dot-circle"></i></div>
                    </div>
</code>```

CSS

```<code>  .user-box .user-img {  position: relative;  height: 88px; width: 88px; margin: 0px auto; }

#wrapper.enlarged .user-box .user-img {  height: 48px;  width: 48px; }
</code>```

答:
Put image as background-image and set it to fill your div, that way you get cutoff where dimension does not fit:

div {
  background: url('http://lorempixel.com/100/200') no-repeat center center;
  background-size: 100%;

  width: 200px;
  height: 200px;
  border: 1px solid red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

Title: Resize url image to equal parts

Body:
I need help with an html / css
in my application to upload the photo in the profile, the user needs to pass the url of the image, I save this url in the database and put this url in my HTML $ {user.fotoProfile}

however, when the image comes with equal proportions, eg. 150x150, 650x650, 960x960 whatever. the setup works and fills my field without distortion.

but when the image does not have equal proportions, the image field is distorted.

Can someone help me?

HTML

                        <img src="<c:url value="${user.fotoProfile}" />" alt="user-img" class="img-circle img-thumbnail img-responsive">

CSS

  .user-box .user-img {  position: relative;  height: 88px; width: 88px; margin: 0px auto; }

#wrapper.enlarged .user-box .user-img {  height: 48px;  width: 48px; }

Body:
Put image as background-image and set it to fill your div, that way you get cutoff where dimension does not fit:

div {
  background: url('http://lorempixel.com/100/200') no-repeat center center;
  background-size: 100%;

  width: 200px;
  height: 200px;
  border: 1px solid red;
}

<div></div>


问:
How to access 'this' in Vuex store module state
For example, say I have a "store" directory like this:

```<code>...
store
├── auth
│   └── user.js
└── index.js
...
</code>```

index.js

```<code>import Vue from 'vue';
import Vuex from 'vuex';
import {user} from './auth/user';

Vue.use(Vuex);

/* eslint-disable no-new */
const store = new Vuex.Store({
  modules: {
    user
  },
});

export default store;
</code>```

Now in the user store I have some constants and other state variables in it's state prop. How can I access state props from within itself? For example user store may look like this:

user.js

```<code>export const user = {
  namespaced: true,

  state: {

    // hardcoded string assigned to user.state.constants.SOME_CONST
    constants: {
      SOME_CONST: 'testString'
    },

    // Another property where I would like to reference the constant above

    someOtherStateProp: {

      // Trying to access the constant in any of these ways throws
      // 'Uncaught ReferenceError: .... undefined'
      // Where '...' above is interchangeable with any root I try to access the constant from (this, state etc)

      test1: this.state.constants.SOME_CONST,
      test2: user.state.constants.SOME_CONST
      test3: state.constants.SOME_CONST
      test4: constants.SOME_CONST
      test5: SOME_CONST
      // .... etc. All the above throw ReferenceError's
    }
  }
};
</code>```

How can I reference user.state.constants.SOME_CONST from user.state.someOtherStateProp.test1?

Feel like I'm missing something very fundamental here.

答:
The simplest way would be declarimg  the CONSTANTS object before exporting your module amd acceessing them as below

```<code>const CONSTANTS = {
    SOME_CONST: 'testString'
}

export const user = {
  namespaced: true,

  state: {

    // hardcoded string assigned to user.state.constants.SOME_CONST
    constants: CONSTANTS,

    // Another property where I would like to reference the constant above

    someOtherStateProp: {

      test1: CONSTANTS.SOME_CONST,
    }
  }
};
</code>```

Body:
For example, say I have a "store" directory like this:

...
store
├── auth
│   └── user.js
└── index.js
...

index.js

import Vue from 'vue';
import Vuex from 'vuex';
import {user} from './auth/user';

Vue.use(Vuex);

/* eslint-disable no-new */
const store = new Vuex.Store({
  modules: {
    user
  },
});

export default store;

Now in the user store I have some constants and other state variables in it's state prop. How can I access state props from within itself? For example user store may look like this:

user.js

export const user = {
  namespaced: true,

  state: {

    // hardcoded string assigned to user.state.constants.SOME_CONST
    constants: {
      SOME_CONST: 'testString'
    },

    // Another property where I would like to reference the constant above

    someOtherStateProp: {

      // Trying to access the constant in any of these ways throws
      // 'Uncaught ReferenceError: .... undefined'
      // Where '...' above is interchangeable with any root I try to access the constant from (this, state etc)

      test1: this.state.constants.SOME_CONST,
      test2: user.state.constants.SOME_CONST
      test3: state.constants.SOME_CONST
      test4: constants.SOME_CONST
      test5: SOME_CONST
      // .... etc. All the above throw ReferenceError's
    }
  }
};

How can I reference user.state.constants.SOME_CONST from user.state.someOtherStateProp.test1?

Feel like I'm missing something very fundamental here.

Body:
The simplest way would be declarimg  the CONSTANTS object before exporting your module amd acceessing them as below

const CONSTANTS = {
    SOME_CONST: 'testString'
}

export const user = {
  namespaced: true,

  state: {

    // hardcoded string assigned to user.state.constants.SOME_CONST
    constants: CONSTANTS,

    // Another property where I would like to reference the constant above

    someOtherStateProp: {

      test1: CONSTANTS.SOME_CONST,
    }
  }
};


问:
multi-tenant application in spring - connecting to DB

Hi Experts,

I am working on a multi-tenant project. It's a table per tenant architecture.

We are using spring and JPA (eclipse-link) for this purpose.
Here our use case is when ever a new customer subscribes to our application a new data base would be created for the customer.

As spring configuration would be loaded only during start-up how to load this new db configuration at run time?

Could some one please give some pointers?
Thanks in advance.

BR,
kitty

答:
For multitenan, first you need to create MultitenantConfig.java
like below file.
here tenants.get("Musa") is my tenant name, comes from application.properties file

```<code> @Configuration
    @EnableConfigurationProperties(MultitenantProperties.class)
    public class MultiTenantConfig extends WebMvcConfigurerAdapter {

        /** The Constant log. */
        private static final Logger log = LoggerFactory.getLogger(MultiTenantConfig.class);

        /** The multitenant config. */
        @Autowired
        private MultitenantProperties multitenantConfig;

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new MultiTenancyInterceptor());
        }

        /**
         * Data source.
         *
         * @return the data source
         */
        @Bean
        public DataSource dataSource() {

            Map<Object, Object> tenants = getTenants();

            MultitenantDataSource multitenantDataSource = new MultitenantDataSource();
            multitenantDataSource.setDefaultTargetDataSource(tenants.get("Musa"));
            multitenantDataSource.setTargetDataSources(tenants);

            // Call this to finalize the initialization of the data source.
            multitenantDataSource.afterPropertiesSet();

            return multitenantDataSource;
        }

        /**
         * Gets the tenants.
         *
         * @return the tenants
         */
        private Map<Object, Object> getTenants() {
            Map<Object, Object> resolvedDataSources = new HashMap<>();

            for (Tenant tenant : multitenantConfig.getTenants()) {
                DataSourceBuilder dataSourceBuilder = new DataSourceBuilder(this.getClass().getClassLoader());
                dataSourceBuilder.driverClassName(tenant.getDriverClassName()).url(tenant.getUrl())
                        .username(tenant.getUsername()).password(tenant.getPassword());
                DataSource datasource = dataSourceBuilder.build();

                for (String prop : tenant.getTomcat().keySet()) {
                    try {
                        BeanUtils.setProperty(datasource, prop, tenant.getTomcat().get(prop));
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        log.error("Could not set property " + prop + " on datasource " + datasource);
                    }
                }

                log.info(datasource.toString());
                resolvedDataSources.put(tenant.getName(), datasource);
            }

            return resolvedDataSources;
        }

    }

public class MultitenantDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return TenantContext.getCurrentTenant();
    }
}

public class MultiTenancyInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
        TenantContext.setCurrentTenant("Musa");
        return true;
    }
}

 @ConfigurationProperties(prefix = "multitenancy")
public class MultitenantProperties {

    public static final String CURRENT_TENANT_IDENTIFIER = "tenantId";
    public static final int CURRENT_TENANT_SCOPE = 0;

    private List<Tenant> tenants;

    public List<Tenant> getTenants() {
        return tenants;
    }

    public void setTenants(List<Tenant> tenants) {
        this.tenants = tenants;
    }
}

  public class Tenant {

    private String name;
    private String url;
    private String driverClassName;
    private String username;
    private String password;
    private Map<String,String> tomcat;

//setter gettter
</code>```

```<code>public class TenantContext {
    private static ThreadLocal<Object> currentTenant = new ThreadLocal<>();
    public static void setCurrentTenant(Object tenant) {
        currentTenant.set(tenant);
    }
    public static Object getCurrentTenant() {
        return currentTenant.get();
    }
}
</code>```

add below properties in application.properties

```<code>multitenancy.tenants[0].name=Musa
multitenancy.tenants[0].url<url>
multitenancy.tenants[0].username=<username>
multitenancy.tenants[0].password=<password>
multitenancy.tenants[0].driver-class-name=<driverclass>
</code>```

Body:
For multitenan, first you need to create MultitenantConfig.java
like below file.
here tenants.get("Musa") is my tenant name, comes from application.properties file

 @Configuration
    @EnableConfigurationProperties(MultitenantProperties.class)
    public class MultiTenantConfig extends WebMvcConfigurerAdapter {

        /** The Constant log. */
        private static final Logger log = LoggerFactory.getLogger(MultiTenantConfig.class);

        /** The multitenant config. */
        @Autowired
        private MultitenantProperties multitenantConfig;

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new MultiTenancyInterceptor());
        }

        /**
         * Data source.
         *
         * @return the data source
         */
        @Bean
        public DataSource dataSource() {

            Map<Object, Object> tenants = getTenants();

            MultitenantDataSource multitenantDataSource = new MultitenantDataSource();
            multitenantDataSource.setDefaultTargetDataSource(tenants.get("Musa"));
            multitenantDataSource.setTargetDataSources(tenants);

            // Call this to finalize the initialization of the data source.
            multitenantDataSource.afterPropertiesSet();

            return multitenantDataSource;
        }

        /**
         * Gets the tenants.
         *
         * @return the tenants
         */
        private Map<Object, Object> getTenants() {
            Map<Object, Object> resolvedDataSources = new HashMap<>();

            for (Tenant tenant : multitenantConfig.getTenants()) {
                DataSourceBuilder dataSourceBuilder = new DataSourceBuilder(this.getClass().getClassLoader());
                dataSourceBuilder.driverClassName(tenant.getDriverClassName()).url(tenant.getUrl())
                        .username(tenant.getUsername()).password(tenant.getPassword());
                DataSource datasource = dataSourceBuilder.build();

                for (String prop : tenant.getTomcat().keySet()) {
                    try {
                        BeanUtils.setProperty(datasource, prop, tenant.getTomcat().get(prop));
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        log.error("Could not set property " + prop + " on datasource " + datasource);
                    }
                }

                log.info(datasource.toString());
                resolvedDataSources.put(tenant.getName(), datasource);
            }

            return resolvedDataSources;
        }

    }

public class MultitenantDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return TenantContext.getCurrentTenant();
    }
}

public class MultiTenancyInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
        TenantContext.setCurrentTenant("Musa");
        return true;
    }
}

 @ConfigurationProperties(prefix = "multitenancy")
public class MultitenantProperties {

    public static final String CURRENT_TENANT_IDENTIFIER = "tenantId";
    public static final int CURRENT_TENANT_SCOPE = 0;

    private List<Tenant> tenants;

    public List<Tenant> getTenants() {
        return tenants;
    }

    public void setTenants(List<Tenant> tenants) {
        this.tenants = tenants;
    }
}

  public class Tenant {

    private String name;
    private String url;
    private String driverClassName;
    private String username;
    private String password;
    private Map<String,String> tomcat;

//setter gettter

public class TenantContext {
    private static ThreadLocal<Object> currentTenant = new ThreadLocal<>();
    public static void setCurrentTenant(Object tenant) {
        currentTenant.set(tenant);
    }
    public static Object getCurrentTenant() {
        return currentTenant.get();
    }
}

add below properties in application.properties

multitenancy.tenants[0].name=Musa
multitenancy.tenants[0].url<url>
multitenancy.tenants[0].username=<username>
multitenancy.tenants[0].password=<password>
multitenancy.tenants[0].driver-class-name=<driverclass>


问:
Use WaitHandle in CountdownEvent
I have simple application that illustrates CountdownEvent. It is fine, but I would like somehow to set WaitHandle of CountDownEvent and use it. Is it possible?  How to achieve that? I suppose I should register WaitHandle and pass it to CountDownEvent?

```<code>public static CountdownEvent _countDwn = new CountdownEvent(3);

static void Main(string[] args)
{
    new Thread(say).Start("hello 1");
    new Thread(say).Start("hello 2");
    new Thread(say).Start("hello 3");
    _countDwn.Wait();

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

public static void Go(object data, bool timedOut)
{
    Console.WriteLine("Started - " + data);
    // Perform task...
}

public static void say(Object o)
{
    Thread.Sleep(4000);
    Console.WriteLine(o);
    _countDwn.Signal();
}
</code>```

UPD

I would like to get something similar to sample with ManualResetEvent. No blocking wait():

```<code>static ManualResetEvent _starter = new ManualResetEvent (false);

public static void Main()
{
  RegisteredWaitHandle reg = ThreadPool.RegisterWaitForSingleObject
                             (_starter, Go, "Some Data", -1, true);
  Thread.Sleep (5000);
  Console.WriteLine ("Signaling worker...");
  _starter.Set();
  Console.ReadLine();
  reg.Unregister (_starter);    // Clean up when we’re done.
}

public static void Go (object data, bool timedOut)
{
  Console.WriteLine ("Started - " + data);
  // Perform task...
}
</code>```

答:
You can use the same way you use for ManualResetEvent:

```<code> RegisteredWaitHandle reg = ThreadPool.RegisterWaitForSingleObject
                         (_countDwn.WaitHandle, Go, "Some Data", -1, true);
 /// ...

 reg.Unregister(_countDwn.WaitHandle);
</code>```

Title: Use WaitHandle in CountdownEvent

Body:
I have simple application that illustrates CountdownEvent. It is fine, but I would like somehow to set WaitHandle of CountDownEvent and use it. Is it possible?  How to achieve that? I suppose I should register WaitHandle and pass it to CountDownEvent?

public static CountdownEvent _countDwn = new CountdownEvent(3);

static void Main(string[] args)
{
    new Thread(say).Start("hello 1");
    new Thread(say).Start("hello 2");
    new Thread(say).Start("hello 3");
    _countDwn.Wait();

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

public static void Go(object data, bool timedOut)
{
    Console.WriteLine("Started - " + data);
    // Perform task...
}

public static void say(Object o)
{
    Thread.Sleep(4000);
    Console.WriteLine(o);
    _countDwn.Signal();
}

UPD

I would like to get something similar to sample with ManualResetEvent. No blocking wait():

static ManualResetEvent _starter = new ManualResetEvent (false);

public static void Main()
{
  RegisteredWaitHandle reg = ThreadPool.RegisterWaitForSingleObject
                             (_starter, Go, "Some Data", -1, true);
  Thread.Sleep (5000);
  Console.WriteLine ("Signaling worker...");
  _starter.Set();
  Console.ReadLine();
  reg.Unregister (_starter);    // Clean up when we’re done.
}

public static void Go (object data, bool timedOut)
{
  Console.WriteLine ("Started - " + data);
  // Perform task...
}

Body:
You can use the same way you use for ManualResetEvent:

 RegisteredWaitHandle reg = ThreadPool.RegisterWaitForSingleObject
                         (_countDwn.WaitHandle, Go, "Some Data", -1, true);
 /// ...

 reg.Unregister(_countDwn.WaitHandle);


问:
Running TensorBoard on summaries on S3 server
I want to use TensorBoard to visualize results stored on an S3 server, without downloading them to my machine. Ideally, this would work:

```<code>$ tensorboard --logdir s3://mybucket/summary
</code>```

Assuming the tfevents files are stored under summary. However this does not work and returns UnimplementedError: File system scheme s3 not implemented.

Is there some workaround to enable TensorBoard to access the data on the server?

答:
The S3 File system plugin for tensorflow was released in Version 1.4 in early October. You'll need to make sure your tensorflow-tensorboard version is at least pip install tensorflow-tensorboard==0.4.0-rc1

Then you can start the server:

tensorboard --logdir=s3://root-bucket/jobs/4/train

Body:
I want to use TensorBoard to visualize results stored on an S3 server, without downloading them to my machine. Ideally, this would work:

$ tensorboard --logdir s3://mybucket/summary

Assuming the tfevents files are stored under summary. However this does not work and returns UnimplementedError: File system scheme s3 not implemented.

Is there some workaround to enable TensorBoard to access the data on the server?


问:
Python get unique list items
I have a list of dictionaries with millions items, i want to extract only unique items that doesn't have same key name from the list , is there a faster way using threads or something to check in parallel instead sequential, my code as below

Note: my list is list of dictionaries, each dictionary has different keys but they may have the same value of key ['name'], if this matched I should only take one

for example:
lst = [{'name':'x','bar': 1, 'foo': 2}, {'name','z','foo': 3, 'bar': 5}, {'name':x','bar': 33, 'foo': 10}]
 here there are two dictionaries have same name equal x so i will only save one in new list
new_lst  =  [{'name':'x','bar': 1, 'foo': 2}, {'name','z','foo': 3, 'bar': 5}]

```<code>new_lst  = []
for x in lst:
     flag = False
     for n in new_lst:
          if x['name'] == n['name']:
                  flag = True
                  break
     if not flag:
        new_lst.append(x)
</code>```

答:
Since you did not provide an example, it is hard to accurately capture what you want, but you might find the following interesting:

```<code>a = [{'bar': 1, 'foo': 2}, {'foobar': 3, 'bar': 5}]

a = {k: v for subdict in a for k, v in subdict.items()}
print(a)  # {'bar': 5, 'foo': 2, 'foobar': 3}
#            ^ 'bar' appears only once (but value could be either 1 or 5)
#                      ^ 'foobar' is taken from the 1st dict. Does not exist in 2nd.
#                                 ^ 'foo' is taken from the 2nd dict. Does not exist in 1st.
</code>```

What I am proposing here is the flattening of your list and reducing it to a single dict. The duplicates will overwrite themselves (order cannot be guaranteed) automatically.

Alternatively, you could achieve the same with the following (which is simpler to understand):

```<code>res = a[0]
for d in a[1:]:
    res.update(d)  # every dict is <<applied>> to the previous one as an update.
print(res)  # {'bar': 5, 'foo': 2, 'foobar': 3}
</code>```

NOTE

My solutions above assume that you do not care about preserving the dict-in-list schema.

Title: Python get unique list items

Body:
I have a list of dictionaries with millions items, i want to extract only unique items that doesn't have same key name from the list , is there a faster way using threads or something to check in parallel instead sequential, my code as below

Note: my list is list of dictionaries, each dictionary has different keys but they may have the same value of key ['name'], if this matched I should only take one

for example:
lst = [{'name':'x','bar': 1, 'foo': 2}, {'name','z','foo': 3, 'bar': 5}, {'name':x','bar': 33, 'foo': 10}]
 here there are two dictionaries have same name equal x so i will only save one in new list
new_lst  =  [{'name':'x','bar': 1, 'foo': 2}, {'name','z','foo': 3, 'bar': 5}]

new_lst  = []
for x in lst:
     flag = False
     for n in new_lst:
          if x['name'] == n['name']:
                  flag = True
                  break
     if not flag:
        new_lst.append(x)

Body:
Since you did not provide an example, it is hard to accurately capture what you want, but you might find the following interesting:

a = [{'bar': 1, 'foo': 2}, {'foobar': 3, 'bar': 5}]

a = {k: v for subdict in a for k, v in subdict.items()}
print(a)  # {'bar': 5, 'foo': 2, 'foobar': 3}
#            ^ 'bar' appears only once (but value could be either 1 or 5)
#                      ^ 'foobar' is taken from the 1st dict. Does not exist in 2nd.
#                                 ^ 'foo' is taken from the 2nd dict. Does not exist in 1st.

What I am proposing here is the flattening of your list and reducing it to a single dict. The duplicates will overwrite themselves (order cannot be guaranteed) automatically.

Alternatively, you could achieve the same with the following (which is simpler to understand):

res = a[0]
for d in a[1:]:
    res.update(d)  # every dict is <<applied>> to the previous one as an update.
print(res)  # {'bar': 5, 'foo': 2, 'foobar': 3}

NOTE

My solutions above assume that you do not care about preserving the dict-in-list schema.


问:
MsTest.exe not finding any tests
I have a selenium Specflow c# project in which I can execute tests from the test explorer and via the ReSharper unit test explorer.

But when I run the command line to execute tests (This is how Jenkins execute tests)

It does not find any tests in the DLL

```<code>mstest /testcontainer:MoneyUITests.dll /test:NavigateToLoans
Microsoft (R) Test Execution Command Line Tool Version 15.0.26621.2
Copyright (c) Microsoft Corporation. All rights reserved.

Loading MoneyUITests.dll...
Test NavigateToLoans cannot be found.
Test NavigateToLoans cannot be found.
Starting execution...
No tests to execute.
</code>```

Not sure what I have done wrong, it seems strange that visual studio managed to find and execute the tests with no issue.

答:
This is because mstest.exe was used for testing in Visual Studio 2010
Since Visual Studio 2012 you should use VSTest.Console.exe.

Have you tried using VSTest.Console.exe instead of mstest.exe?

I found this answer already on stackoverflow: Answer on How to run selenium c# test in command prompt?

Title: MsTest.exe not finding any tests

Body:
I have a selenium Specflow c# project in which I can execute tests from the test explorer and via the ReSharper unit test explorer.

But when I run the command line to execute tests (This is how Jenkins execute tests)

It does not find any tests in the DLL

mstest /testcontainer:MoneyUITests.dll /test:NavigateToLoans
Microsoft (R) Test Execution Command Line Tool Version 15.0.26621.2
Copyright (c) Microsoft Corporation. All rights reserved.

Loading MoneyUITests.dll...
Test NavigateToLoans cannot be found.
Test NavigateToLoans cannot be found.
Starting execution...
No tests to execute.

Not sure what I have done wrong, it seems strange that visual studio managed to find and execute the tests with no issue.


问:
flash[:notice] or flash.notice?
FlashHash has convenience methods for :notice and :alert. My question then is, which is most appropriate? flash[:notice] or flash.notice? Is it simply a mater of taste or this there a compelling reason to chose one method over the other?</p>

答:
```<code># File actionpack/lib/action_dispatch/middleware/flash.rb, line 150
150:       def notice
151:         self[:notice]
152:       end
</code>```

I knew it!

Title: flash[:notice] or flash.notice?

Body:
# File actionpack/lib/action_dispatch/middleware/flash.rb, line 150
150:       def notice
151:         self[:notice]
152:       end

I knew it!


问:
An unhandled exception occurred while trying to save new data
I'm trying to save the changes changes for a question and answer project I am creating. I can't save Tags because it returns an exception whenever I query if the data already exists.

```<code> public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
        }

    public DbSet<ApplicationUser> ApplicationUsers { get; set; }
    public DbSet<Question> Questions { get; set; }
    public DbSet<Tag> Tags { get; set; }
    public DbSet<QuestionTag> QuestionTags { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<QuestionTag>()
                    .HasKey(t => new { t.QuestionID, t.TagID });

        modelBuilder.Entity<QuestionTag>()
            .HasOne(qt => qt.Question)
            .WithMany(q => q.QuestionTags)
            .HasForeignKey(qt => qt.QuestionID);

        modelBuilder.Entity<QuestionTag>()
            .HasOne(qt => qt.Tag)
            .WithMany(t => t.QuestionTags)
            .HasForeignKey(qt => qt.TagID);
}
</code>```

Here is the code I use to Parse new Data while querying if the Tags already exist.

```<code>public List<QuestionTag> ParseTags(string tags)
        {
            var tagList = tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
        var questionTags = new List<QuestionTag>();
        var anyNewTags = false;

        foreach (var tag in tagList)
        {
            var tagExists = _context.Tags.Where(x => x.Name == tag)
                .Select(x => new QuestionTag { Tag = new Tag { Name = x.Name } })
                .FirstOrDefault();

            if (tagExists == null)
            {
                var newTag = new QuestionTag() { Tag = new Tag() { Name = tag } };
                _context.QuestionTags.Add(newTag);
                questionTags.Add(newTag);

                anyNewTags = true;
            }else
            {

                questionTags.Add(tagExists);
            }

        }
            if (anyNewTags) _context.SaveChanges();
        return questionTags;
    }
</code>```

But Instead, I get this Error when I try to parse in new Tags:
InvalidOperationException: The property 'QuestionID' on entity type 'QuestionTag' has a temporary value. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.

答:
The error directs you that you should set QuestionID property to establish assosication with Question entity. So try to set a value to QuestionId property.

```<code>var newTag = new QuestionTag() { Tag = new Tag() { Name = tag }, QuestionId = questionId };
_context.QuestionTags.Add(newTag);
</code>```

Note : I wrote questionId variable for making an example. You should set it with related ID of Question entity.

Body:
I'm trying to save the changes changes for a question and answer project I am creating. I can't save Tags because it returns an exception whenever I query if the data already exists.

 public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
        }

    public DbSet<ApplicationUser> ApplicationUsers { get; set; }
    public DbSet<Question> Questions { get; set; }
    public DbSet<Tag> Tags { get; set; }
    public DbSet<QuestionTag> QuestionTags { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<QuestionTag>()
                    .HasKey(t => new { t.QuestionID, t.TagID });

        modelBuilder.Entity<QuestionTag>()
            .HasOne(qt => qt.Question)
            .WithMany(q => q.QuestionTags)
            .HasForeignKey(qt => qt.QuestionID);

        modelBuilder.Entity<QuestionTag>()
            .HasOne(qt => qt.Tag)
            .WithMany(t => t.QuestionTags)
            .HasForeignKey(qt => qt.TagID);
}

Here is the code I use to Parse new Data while querying if the Tags already exist.

public List<QuestionTag> ParseTags(string tags)
        {
            var tagList = tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
        var questionTags = new List<QuestionTag>();
        var anyNewTags = false;

        foreach (var tag in tagList)
        {
            var tagExists = _context.Tags.Where(x => x.Name == tag)
                .Select(x => new QuestionTag { Tag = new Tag { Name = x.Name } })
                .FirstOrDefault();

            if (tagExists == null)
            {
                var newTag = new QuestionTag() { Tag = new Tag() { Name = tag } };
                _context.QuestionTags.Add(newTag);
                questionTags.Add(newTag);

                anyNewTags = true;
            }else
            {

                questionTags.Add(tagExists);
            }

        }
            if (anyNewTags) _context.SaveChanges();
        return questionTags;
    }

But Instead, I get this Error when I try to parse in new Tags:
InvalidOperationException: The property 'QuestionID' on entity type 'QuestionTag' has a temporary value. Either set a permanent value explicitly or ensure that the database is configured to generate values for this property.

Body:
The error directs you that you should set QuestionID property to establish assosication with Question entity. So try to set a value to QuestionId property.

var newTag = new QuestionTag() { Tag = new Tag() { Name = tag }, QuestionId = questionId };
_context.QuestionTags.Add(newTag);

Note : I wrote questionId variable for making an example. You should set it with related ID of Question entity.


问:
Selenium - WebElement object has no attribute 'sendKeys'
I'm trying to enter text into an input field using selenium but it's giving an error. The code is:

```<code>input1 = browser.find_element_by_xpath('//*[@id="login-dialog dialog"]/div[2]/div[2]/div[2]/form/div[1]/input')
input1.sendKeys("myusername")
</code>```

However it gives this error

```<code>Traceback (most recent call last):
File "C:\Users\Bradley Jo\Desktop\Project\app.py", line 14, in
<module>
input1.sendKeys("hello")
AttributeError: 'WebElement' object has no attribute 'sendKeys'
</code>```

答:
You have to use actions instead of direct typing in input field.
Please use the below portion of code

```<code>input1 = browser.find_element_by_xpath('//*[@id="login-dialog dialog"]/div[2]/div[2]/div[2]/form/div[1]/input')

actions = ActionChains(driver)
actions.move_to_element(input1).send_keys("myusername").perform()
</code>```

If the browser is your driver then change driver with browser.

Body:
I'm trying to enter text into an input field using selenium but it's giving an error. The code is:

input1 = browser.find_element_by_xpath('//*[@id="login-dialog dialog"]/div[2]/div[2]/div[2]/form/div[1]/input')
input1.sendKeys("myusername")

However it gives this error

Traceback (most recent call last):
File "C:\Users\Bradley Jo\Desktop\Project\app.py", line 14, in
<module>
input1.sendKeys("hello")
AttributeError: 'WebElement' object has no attribute 'sendKeys'

Body:
You have to use actions instead of direct typing in input field.
Please use the below portion of code

input1 = browser.find_element_by_xpath('//*[@id="login-dialog dialog"]/div[2]/div[2]/div[2]/form/div[1]/input')

actions = ActionChains(driver)
actions.move_to_element(input1).send_keys("myusername").perform()

If the browser is your driver then change driver with browser.