探索与发现

研究java技术

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  83 随笔 :: 0 文章 :: 109 评论 :: 0 Trackbacks

#

http://www.cnblogs.com/netcai/archive/2008/09/11/1288897.html
posted @ 2009-02-13 08:30 蜘蛛 阅读(917) | 评论 (5)编辑 收藏

http://www.cnblogs.com/netcai/archive/2008/12/17/1357157.html
posted @ 2009-02-13 08:23 蜘蛛 阅读(462) | 评论 (0)编辑 收藏

http://www.cnblogs.com/wangzhiyang/archive/2009/02/02/1382490.html
posted @ 2009-02-13 08:17 蜘蛛 阅读(180) | 评论 (0)编辑 收藏

Enterprise Library 4.1 - October 2008
Logging QuickStart

The Logging QuickStart demonstrates the following scenarios:

The QuickStart uses a top-level handler to catch any exceptions that occur during any of the scenarios. The handler displays a dialog box with the exception message.

The QuickStart is provided in two versions. The first version uses the factory approach to create Enterprise Library objects and the static methods. For example, it uses the static Write method of the Logger class to write log messages and the static Tracer class to trace operations such as data access and write messages to a file.

The second version demonstrates integration with the Unity Application Block. It creates and populates a UnityContainer instance with the data from the <unity> section of the configuration file. This loads the Enterprise Library Core and Logging Application Block extensions. This QuickStart also generates the main form instance using the Resolve method of the UnityContainer, which causes Unity to create and inject an instance of the LogWriter and non-static TraceManager classes in the form constructor. The QuickStart then uses the methods of these two instances to perform the tasks required. For example, it uses the Write method of the LogWriter class to write log messages and the StartTrace method of the non-static TraceManager class to trace operations such as data access and write messages to a file.

For information about integration with the Unity Application Block, and how you can create instances of Enterprise Library objects using Unity, see Creating Objects Using the Unity Application Block.

The QuickStart ships as source code, which means that you must compile it before running it. You use Visual Studio to build the QuickStart.

To build the Logging QuickStart

  1. Ensure the Enterprise Library Source Code is installed.
  2. Open the Enterprise Library Source Code folder in Windows Explorer or from the Start menu. To open it from the Start menu, click Start on the taskbar, point to All Programs, point to Microsoft patterns & practices, point to Enterprise Library 4.1October 2008, and then click Enterprise Library 4.1 Source Folder.
  3. To run the factory version of the QuickStart, open the QuickStarts folder, open the Logging folder, and then open the CS folder (for C#) or the VB folder (for Visual Basic .NET).
  4. To run the version of the QuickStart that demonstrates integration with the Unity Application Block, open the QuickStarts folder, open the Logging folder, and then open the CS - UnityIntegration folder (for C#) or the VB - UnityIntegration folder (for Visual Basic .NET).
  5. Double-click the LoggingQuickStart.sln icon.
  6. Visual Studio opens, displaying the solution file. On the Build menu, click Rebuild Solution. By default, this is a debug build.
  7. Press F5 to run the QuickStart.

The default configuration for the Logging QuickStart has the following attributes:

  • General settings:
    • Tracing is enabled.
    • The default category is General.
  • Filters:
    • The category filter will allow all categories except UI Events.
    • The priority filter will only allow events with a priority value of 2 or higher
  • Categories:
    • Events in category Data Access Events are delivered to the Flat File Destination listener.
    • Events in category Debug are delivered to the Debug Destination listener.
    • Events in category General are delivered to the Event Log Destination listener.
    • Events in category Troubleshooting are delivered to the Event Log Destination listener.
    • Events in category UI Events are delivered to the Flat File Destination listener.
    • Events in category Trace are delivered to the Flat File Destination listener.
  • Special sources:
    • Events that occur due to an error are delivered to the Event Log Destination.
  • Listeners:
    • The Event Log Destination uses the Text Formatter to format the message and writes the result to the Application Event Log.
    • The Flat File Destination uses the Text Formatter to format the message and writes the result to the file named trace.log.
    • The Debug Destination uses the Text Formatter to format the message and writes the result to the Visual Studio Output Window.
  • Formatters:
    • The Text Formatter constructs a string with name value pairs for the LogEntry properties.

The Logging QuickStart ships with a defined configuration, which is included in the App.config file. This file is located in the same folder as the QuickStart project file. Each time you build the code, Visual Studio copies the App.config file to the output directory for the project (the same directory where the QuickStart executable is created), and renames it to LoggingQuickStart.exe.config.

To change or view these settings, use the Enterprise Library configuration tools to open the App.config file in the directory that contains the QuickStart project file. The App.config file contains the configuration data.

You can also change the application configuration when you do not plan to recompile the application by opening the LoggingQuickStart.exe.config file with the Enterprise Library configuration tools. However, these changes will be overwritten during the next successful build.

posted @ 2009-02-11 07:20 蜘蛛 阅读(1236) | 评论 (1)编辑 收藏

I have used log4net in numerous projects over the years.

Recently I have been working in MOSS 2007, creating timer jobs, and I certainly saw the value in having a great logging tool like log4net at my disposal.

The timer job will be executed by Windows SharePoint Services Timer service. The service by default runs under the Network Service account.

You will need to put log4net into the GAC. The default log4net distribution comes with a signed assembly for this purpose.

Given that your assembly of the Timer job will live inside the GAC as well, I found that the easiest route was to configure log4net in code.  That way we don't have to worry about an extra configuration file.

My preferred logging target in log4net is a database, so the example will log to a dedicated database.

The following function can be used to programmatically configure log4net with one database appender, and selective filtering

public void ConfigureLog4Net(string _LOGGING_CONNECTIONSTRING,bool DEBUGINFO)
{
AdoNetAppender sqlAppender = new AdoNetAppender();
sqlAppender.CommandType = CommandType.Text;
sqlAppender.ConnectionType = "System.Data.SqlClient.SqlConnection, System.Data,Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
sqlAppender.ConnectionString = _LOGGING_CONNECTIONSTRING;
sqlAppender.CommandText = "INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message,@exception)";

AdoNetAppenderParameter param1 = new AdoNetAppenderParameter();
param1.ParameterName = "@log_date";
param1.Layout = new log4net.Layout.RawTimeStampLayout();
param1.DbType = DbType.DateTime;
sqlAppender.AddParameter(param1);

AdoNetAppenderParameter param2 = new AdoNetAppenderParameter();
param2.ParameterName = "@log_level";
param2.Layout = new Layout2RawLayoutAdapter(new log4net.Layout.PatternLayout("%level"));
param2.DbType = DbType.String;
param2.Size = 50;
sqlAppender.AddParameter(param2);
AdoNetAppenderParameter param3 = new AdoNetAppenderParameter();
param3.ParameterName = "@thread";
param3.Layout = new Layout2RawLayoutAdapter(new log4net.Layout.PatternLayout("%thread"));
param3.DbType = DbType.String;
param3.Size = 255;
sqlAppender.AddParameter(param3);

 

AdoNetAppenderParameter param4 = new AdoNetAppenderParameter();
param4.ParameterName = "@logger";
param4.Layout = new Layout2RawLayoutAdapter(new log4net.Layout.PatternLayout("%logger"));
param4.DbType = DbType.String;
param4.Size = 255;
sqlAppender.AddParameter(param4);

AdoNetAppenderParameter param5 = new AdoNetAppenderParameter();
param5.ParameterName = "@message";
param5.DbType = DbType.String;
param5.Layout = new Layout2RawLayoutAdapter(new log4net.Layout.PatternLayout("%message"));
param5.Size = 4000;
sqlAppender.AddParameter(param5);

AdoNetAppenderParameter param6 = new AdoNetAppenderParameter();
param6.ParameterName = "@exception";
param6.DbType = DbType.String;
param6.Layout = new Layout2RawLayoutAdapter(new log4net.Layout.ExceptionLayout());
param6.Size = 4000;
sqlAppender.AddParameter(param6);

log4net.Filter.LevelRangeFilter filter = new log4net.Filter.LevelRangeFilter();

if (!DEBUGINFO)
{
filter.LevelMin = log4net.Core.Level.Warn;
filter.LevelMax = log4net.Core.Level.Critical;
sqlAppender.AddFilter(filter);
}

sqlAppender.BufferSize = 1;
sqlAppender.ActivateOptions();

BasicConfigurator.Configure(sqlAppender);
}

 

The schema for the database the code uses is:

CREATE TABLE [dbo].[Log](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [Date] [datetime] NOT NULL,
 [Thread] [varchar](255) NOT NULL,
 [Level] [varchar](50) NOT NULL,
 [Logger] [varchar](255) NOT NULL,
 [Message] [varchar](4000) NOT NULL,
 [Exception] [varchar](2000) NULL
) ON [PRIMARY]

posted @ 2009-02-11 07:10 蜘蛛 阅读(360) | 评论 (0)编辑 收藏

I had previously written about using lo4net from Sharepoint
by including all the configuration settings in the code.

This certainly works, and its very easy.

It would be good to be able to use a standard log4net configuration
file though. In fact that would be great.

And you can.

FileInfo configFile = new FileInfo(_LOG4NET_CONFIGURATIONFILE);
XmlConfigurator.Configure(configFile);

It is that simple.

In the code above _LOG4NET_CONFIGURATIONFILE is a configuration setting I read from the Sharepoint configuration file, but you can hardcode it instead.           

You have to make sure that you put the configuration file in a location that Sharepoint can read from .

One such place is

C:\Inetpub\wwwroot\wss\VirtualDirectories\80

I find it tidy to keep the log4net file next to the web.config file as well.

You can also read from the web.config file that Sharepoint uses with this code:

Configuration config = null;
config = WebConfigurationManager.OpenWebConfiguration("/", "Sharepoint - 80");

 

 

 

Phil Haack explains configuring log4net in asp.net 2.0 application. We can keep the configuration in the web.config, and we need to tell the log4net, that where we kept the configuration in the Application_Start() event using XmlConfiguration.Configure() menthod. In asp.net we can add a Global.asax and keep this code in Global.asax.cs.

But how can we do this in Sharepoint?

Every site collection we create in sharepoint, creates a globals.asax file and keeps in the webapp root directory. The asax files contains the following code.

<%@ Assembly Name="Microsoft.SharePoint"%>
<%@ Application Language="C#" Inherits="Microsoft.SharePoint.ApplicationRuntime.SPHttpApplication" %>

We can add a inline code in the global.asax file as follows,

<%@ Assembly Name="Microsoft.SharePoint"%>
<%@ Assembly Name="log4net, version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" %>
<%@ Application Language="C#" Inherits="Microsoft.SharePoint.ApplicationRuntime.SPHttpApplication" %>
<%@ Import Namespace="log4net.Config" %>

<script runat="server">
void Application_Start(Object sender, EventArgs e)
{

// Configure log4Net, to take its configuration from the web.config file.
XmlConfigurator.Configure();
}
</script>

or we can derive a class from SPHttpApplication and add the Application_Start() method.

 

posted @ 2009-02-11 07:09 蜘蛛 阅读(354) | 评论 (0)编辑 收藏

Have you ever been working with a good number of applications at once? Are you a naturally born multi tasker? Alright, answer me this - who has had Windows buckle under the weight of all of these applications and display error messages stating that the system is out of memory or out of resources, buttons and menus do not work correctly, or you get an error sound but no message on the screen? I’ve hit this numerous times, to the point that I’ve lost work because of it…

(By the way, Adobe, can you please implement that little feature that Microsoft Office has had for years known as “auto save”? I don’t know how many times I’ve managed to completely max out Windows designing a web site and have had Photoshop fall over dead and disappear off my screen, only to find out that when I open Photoshop up again that the entire thing saved jack-all, all of those layers and documents gone poof into the void of darkness… if Microsoft can do it, why can’t you?)

Sometimes this happens even when you have a lot of system memory (RAM) still available. For instance, open up Internet Explorer and hold Ctrl+N to open up as many Internet Explorer windows as you can before menus, icons, and menus start displaying incorrectly, disappear, buttons aren’t clickable, etc. Close a few out and check your Windows Task Manager in the “Performance” tab, I bet you will find that a lot of your Physical Memory is still available.

This publication applies to:

    * Microsoft Windows 2000 Professional
    * Microsoft Windows 2000 Server
    * Microsoft Windows 2000 Advanced Server
    * Microsoft Windows XP Home Edition
    * Microsoft Windows XP Professional
    * Microsoft Windows XP Professional x64 Edition
    * Microsoft Windows XP Media Center Edition
    * Microsoft Windows XP Tablet PC Edition

DISCLAIMER: mikedopp.com and mikedopp hold no responsibility or liability whatsoever should something go wrong, or if you incorrectly modify the Windows Registry. Please take extreme caution while following this publication and follow the steps correctly.

“Okie-dokie, if I have all of this memory still available, why is Windows saying I’m out of memory and out of system resources!?”

Simple. You have hit the “user handle” or “GDI handle” limit in Windows. This limit is there for two reasons:

    * Leaky applications or faulty code & malware can’t easily crash the system by attempting to overflow the system with GDI handles, making everything un-usable until a reboot is performed.
    * To prevent a user from opening up more applications than the system can handle.

If you have 1 gigabyte (or 1024MB) of RAM or higher, the default User Handle and GDI Handle limits can be pretty restrictive when running a large working set of applications that demand the most from your system and tax it heavily.

“Do you feel my pain?”

Yes, of course. Otherwise, I wouldn’t be writing this article that is more than likely a good 2 or 3 pages in length.

I’m a designer and coder, I use Adobe Photoshop with a lot of documents opened up - on top of that, I usually listen to music while working as it helps me work better, so Windows Media Player 10 is usually open on my machine. Also opened are Windows Messenger, Microsoft Office Outlook 2003, SmartFTP (one of the best FTP clients I’ve ever used, highly recommended), Microsoft Word, a few dozen Internet Explorer windows, some Mozilla Firefox windows with a few tabs opened in each one, and EditPlus 2 for coding.

That’s a pretty heavy working set of applications, and I demand the most out of my computer when it comes to multitasking (I have a Pentium 4 2.66GHz, with 1.5GB of RAM just for those who are wondering).

I too have nailed these handle limits - more than once. After much searching and pondering I have finally come up with a working solution around this issue (hurray!)

“Yeah yeah, stop rambling and cut to the chase!”

First and foremost, I must warn you that modifying these settings incorrectly can render your Windows installation near useless. Also, depending on your computer configuration and the amount of RAM in your system, you may wish to play around with the numbers until you find a setting that is perfect for your computer.

To back up everything, open the Registry Editor (click on Start, Run, and then type “regedit.exe” (without the quotes).

To backup a registry key:

    * In the Registry Editor on the left hand side, you will see the navigation pane. Using your mouse or keyboard, navigate to the following subkeys:

    * HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\SubSystems 
    * HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Windows 
    * Right click on each of the subkeys above in the left hand pane and from the context menu that appears, choose the “Export” option. Save the exported registry data file where ever you wish, but make sure that it will be accessible should we need to restore the files.

“OK, I’ve backed everything up! Now what!?”

Don’t quit the Registry Editor just yet - we still need to make some modifications in order to increase the handle limits in Windows.

With the Registry Editor opened, navigate to HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\SubSystems. You will notice a set of “REG_MULTI_SZ” and “REG_EXPAND_SZ” keys in the right hand pane. The one that we are interested in modifying is called “Windows”.

To modify the key, double click on it. It should look something like this:

    %SystemRoot%\system32\csrss.exe ObjectDirectory=\Windows SharedSection=1024,3072,512 Windows=On SubSystemType=Windows ServerDll=basesrv,1 ServerDll=winsrv:UserServerDllInitialization,3 ServerDll=winsrv:ConServerDllInitialization,2 ProfileControl=Off MaxRequestThreads=16

The section of this string we are interested in modifting is “SharedSection”.

In the SharedSection part of the string you will notice 3 numbers. What we are interested in is the middle value, “3072?. Modify this value so that the middle number is “8192?.

It should look something like this after modifying the value:

    %SystemRoot%\system32\csrss.exe ObjectDirectory=\Windows SharedSection=1024,8192,512 Windows=On SubSystemType=Windows ServerDll=basesrv,1 ServerDll=winsrv:UserServerDllInitialization,3 ServerDll=winsrv:ConServerDllInitialization,2 ProfileControl=Off MaxRequestThreads=16

Now that we’ve changed this, lets continue, shall we?

In the left hand pane of the Registry Editor, navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows. In the right hand side, you will see two REG_DWORD values, named “GDIProcessHandleQuota” and “USERProcessHandleQuota”. We will need to modify both of these.

The first key we will want to modify is “GDIProcessHandleQuota”. This keys value can be set between 256 and 16,384 (maximum), and the default value is 10,000. I’d recommend using 15,000 as a value for this key, however if you are doing a lot of multitasking, shoot for the stars and go with 16,384.

This key can not be set past 16,384 as it is the maximum acceptable value.

Now, lets modify “USERProcessHandleQuota”. This keys value can be set between 200 and 18,000 (maximum), with a default value of 10,000. I’d recommend increasing this value to the same number used with “GDIProcessHandleQuota”, however as previously mentioned if you are working with a hefty application workload, shoot for the stars and go wth the maximum value of 18,000.

This key can not be set past 18,000 as it is the maximum acceptable value.

Do NOT attempt to increase these values past the maximum - Windows will become very unstable and may even stop working correctly. If Windows starts acting up after changing these values, lower them until the issues are resolved, or restore the backups of these keys’ values that we created before making modifications.

Now that you’ve changed these values, restart your computer and tax the system using the Internet Explorer trick mentioned previously - open Internet Explorer and hold down Ctrl+N on your keyboard to open up new Internet Explorer windows. Continue this until menus, buttons, and user interface elements stop working correctly. Also, open any applications you run day-to-day while you are performing this, so that you can get more of an idea if you have everything configured correctly.

You may also want to monitor your memory usage and handles information in Task Manager to see whether or not the above registry values need any more modifications.

I hope this helps with any multi-tasking issues you may have run into while running Microsoft Windows, now get back to work!

posted @ 2008-08-31 20:53 蜘蛛 阅读(479) | 评论 (1)编辑 收藏

rtrim & ltrim,,自己写的。。

public static boolean hasLength(String str)
    {
        return str != null && str.length() > 0;
    }
   
    public static String trimRight(String source){
        if(!hasLength(source))
            return source;
        if(source.trim().length()==0)
            return "";
        int index=0;
        for(int i=source.length()-1;i>=0;i--){
            if(Character.isWhitespace(source.charAt(i))){
                index=i;
            }else{
                break;
            }
        }
        return index!=0 ? source.substring(0,index): source;
    }
   
    public static String trimLeft(String source){
        if(!hasLength(source))
            return source;
        if(source.trim().length()==0)
            return "";
        int index=0;
        for(int i=0;i<source.length();i++){
            if(Character.isWhitespace(source.charAt(i))){
                index=i+1;
            }else{
                break;
            }
        }
        return index!=0 ? source.substring(index): source;
    }

posted @ 2007-09-20 22:58 蜘蛛 阅读(2547) | 评论 (9)编辑 收藏

a=Movie.find(1)
a=Movie.find_by_name("g")
a=Comment.find(:all,:conditions=>"comment like '%thi%'")
posted @ 2007-03-31 16:17 蜘蛛 阅读(609) | 评论 (2)编辑 收藏

ruby里的表对应的三关系:
在mysql里创建两张表
mysql> create table invoices(
    -> id int primary key auto_increment,
    -> order_id int,
    -> created_at timestamp
    -> );
Query OK, 0 rows affected (0.28 sec)

mysql> create table orders(
    -> id int primary key auto_increment,
    -> company varchar(30)
    -> );
Query OK, 0 rows affected (0.23 sec)
(1)one to one relationShip:
   order.rb
   class Order < ActiveRecord::Base
   has_one:invoice
   end

   invoice.rb
   class Invoice < ActiveRecord::Base
    belongs_to:order
   end

   D:\ruby\mytest\mytest1>ruby script\console
   Loading development environment.
   >> order=Order.new
   => #<Order:0x4872e78 @new_record=true, @attributes={"company"=>nil}>
   >> order.company="Big Corp"
   => "Big Corp"
   >> order.save
   => true

   >> invoice=Invoice.new
   => #<Invoice:0x485c5ec @new_record=true, @attributes={"order_id"=>nil, "created_
   at"=>nil}>
   >> order.invoice=invoice
   => #<Invoice:0x485c5ec @errors=#<ActiveRecord::Errors:0x4858730 @errors={}, @bas
   e=#<Invoice:0x485c5ec ...>>, @new_record=false, @attributes={"order_id"=>1, "id"
   =>1, "created_at"=>Sat Mar 31 14:41:32 +0800 2007}>
   >>

(2)one to many
  mysql> create table comments
    -> (
    -> id int primary key auto_increment,
    -> comment varchar(5000),
    -> created_at timestamp,
    -> updated_at timestamp
    -> );
Query OK, 0 rows affected (0.31 sec)

mysql> alter table comments add critic_id int;
Query OK, 0 rows affected (0.42 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> create table critics
    -> (
    -> id  int primary key auto_increment,
    -> firstname varchar(30),
    -> lastname varchar(30),
    -> email varchar(30)
    -> );
Query OK, 0 rows affected (0.11 sec)

class Critic < ActiveRecord::Base
  has_many:comment
end

class Comment < ActiveRecord::Base
  belongs_to:critic
end

D:\ruby\mytest\mytest1>ruby script\console
Loading development environment.
>> a_critic=Critic.new
=> #<Critic:0x486ffd4 @new_record=true, @attributes={"lastname"=>nil, "firstname
"=>nil, "email"=>nil}>
>> a_critic.lastname="adm"
=> "adm"
>> a_critic.save
=> true
>> a_comment=Comment.new
=> #<Comment:0x485a1fc @new_record=true, @attributes={"updated_at"=>nil, "critic
_id"=>nil, "comment"=>nil, "created_at"=>nil}>
>> a_comment.comment="this is a movie"
=> "this is a movie"
>> a_critic.comment<<a_comment


(3)many to many
   有三张表table1s ,table1s_table2s,table2s
   分别在table1.rb,table2.rb增加下面的语句
   has_and_belongs_to_many:table1;
  
has_and_belongs_to_many:table2
操作与(2)相似
posted @ 2007-03-31 16:08 蜘蛛 阅读(464) | 评论 (0)编辑 收藏

仅列出标题
共9页: 上一页 1 2 3 4 5 6 7 8 9 下一页