提供程序模式是一个简单的模式,主要是为了减少代码复用而提高代码重用率而设计的模式,只在.Net框架中提供。ProviderBase是.Net提供的基础类. 它其实是继承的一种变体,从xml中读取各种继承的类的名字,从而一起调用一个基类方法实现不同类的同一行为。
下面是一个例子,用于得到不同酒店的价格。
public abstract class HotelProviderBase : ProviderBase
{
int RunId;
void setProxy(String proxy){}
public abstract void UpdateHotels(JobRequest request, int runId);
}
public sealed class ExampleHotelProvider : HotelProviderBase
{
private void UpdateHotel(JobRequest request){}
}
public abstract class HotelProviderManager
{
private static void LoadProviders()
{
//load class from hotel.xml
_providers = new HotelProviderCollection();
ProvidersHelper.InstantiateProviders(section.Providers, _providers, typeof(HotelProviderBase));
}
}
public sealed class HotelManager
{
public void onRun()
{
foreach (HotelProviderBase provider in HotelProviderManager.Providers)
{
if (provider.Enabled)
{
provider.UpdateHotels(request, (int)Log.RunId);
}
}
}
}
hotel.xml
<add name="ExampleHotelProvider"
type="ExampleHotelProvider"
siteId="4"
siteName="http://www.example.com"
tableName="HotelRates_Example_Hotels">
http://www.cnblogs.com/webabcd/archive/2007/01/22/626479.html
Sunday, May 17, 2015
命令模式Command pattern
由wiki里面的定义,命令模式是把action封装起来,方便重复使用。
下面演示一个测试android app基于UiAutomator的程序
1. EventInput: 首先定义event/command的输入参数
2. Events: 一系列的actions
3. Operator: 对应不同的input,invoke相应的action
4. Main class: 列出所有input, 然后operator开始做事
public abstract class EventInput {
public EventInput followingInput;
}
import java.util.ArrayList;
public class ClickEventInput extends EventInput{
protected String target;
//for GetListValues
public ClickEventInput(){}
public ClickEventInput(EventInput followingInput)
{
this.followingInput = followingInput;
}
public ClickEventInput(String target)
{
this(target,null);
}
public ClickEventInput(String target, EventInput followingInput)
{
this.target = target;
this.followingInput = followingInput;
}
}
public class Events {
protected static Operator op;
protected Events(Operator op)
{
this.op = op;
}
public void Click(UiDevice device, String buttonName, EventInput followingInput) throws UiObjectNotFoundException
{
try
{
if(new UiObject(new UiSelector().text(buttonName)).exists())
new UiObject(new UiSelector().text(buttonName)).clickAndWaitForNewWindow();
}
catch(Exception e)
{
Util.Log(3, "Can't press button", buttonName+","+e.toString());
return;
}
if(followingInput!=null)
op.InvokeAction(followingInput);
}
}
如果有其他行为,写custom类覆盖
public class CarEvents extends Events{
public CarEvents(Operator op) {
super(op);
}
public void Click(UiDevice device, String buttonName, EventInput followingInput) throws UiObjectNotFoundException
{
}
}
public class Operator{
UiDevice device;
EventInput input;
下面演示一个测试android app基于UiAutomator的程序
1. EventInput: 首先定义event/command的输入参数
2. Events: 一系列的actions
3. Operator: 对应不同的input,invoke相应的action
4. Main class: 列出所有input, 然后operator开始做事
public abstract class EventInput {
public EventInput followingInput;
}
import java.util.ArrayList;
public class ClickEventInput extends EventInput{
protected String target;
//for GetListValues
public ClickEventInput(){}
public ClickEventInput(EventInput followingInput)
{
this.followingInput = followingInput;
}
public ClickEventInput(String target)
{
this(target,null);
}
public ClickEventInput(String target, EventInput followingInput)
{
this.target = target;
this.followingInput = followingInput;
}
}
public class Events {
protected static Operator op;
protected Events(Operator op)
{
this.op = op;
}
public void Click(UiDevice device, String buttonName, EventInput followingInput) throws UiObjectNotFoundException
{
try
{
if(new UiObject(new UiSelector().text(buttonName)).exists())
new UiObject(new UiSelector().text(buttonName)).clickAndWaitForNewWindow();
}
catch(Exception e)
{
Util.Log(3, "Can't press button", buttonName+","+e.toString());
return;
}
if(followingInput!=null)
op.InvokeAction(followingInput);
}
}
如果有其他行为,写custom类覆盖
public class CarEvents extends Events{
public CarEvents(Operator op) {
super(op);
}
public void Click(UiDevice device, String buttonName, EventInput followingInput) throws UiObjectNotFoundException
{
}
}
public class Operator{
UiDevice device;
EventInput input;
public void InvokeAction(EventInput input)
{
Class cls = null;
Object value = false;
Class[] constructorArg = new Class[1];
constructorArg[0] = Operator.class;
Object obj = cls.getDeclaredConstructor(constructorArg).newInstance(this);
if(input instanceof ClickEventInput)
{
Method method = null;
Class[] cArg = new Class[3];
cArg[0] = UiDevice.class;
cArg[1] = String.class;
cArg[2] = EventInput.class;
ClickEventInput cInput = (ClickEventInput)input;
method = cls.getMethod("Click",cArg);
method.invoke(obj,device,cInput.target, input.followingInput);
}
}
}
public class NewCar extends UiAutomatorTestCase {
public void testDemo() throws UiObjectNotFoundException {
EventInput input = new ClickEventInput("MAKE & MODEL",,new SleepEventInput(3));
Operator op = new Operator(getUiDevice(), input,"Car", CarEvents.class);
op.Start();
}
}
Saturday, March 21, 2015
Postgres SQL
btim, length: (remove those records with invalid chars only like **()*%0_ )
select * from stocks
where length(btrim(description,' <>=*@_''-?%&()/":`.0'))>0
limit 10000
upper: (case sensitive)
select upper('aa')
replace:
replace('gary sham'.'sham','cen')
concatenate:
string||string
regex:
http://www.postgresql.org/docs/8.3/static/functions-matching.html
--remove price, g means replace all, no g means replace once
update aaa
set des = regexp_replace(des,E'\\$\s*[0-9,\\.]*','------------','g');
--get 1st blocks specified by regex
(regexp_matches(des,E'\\w+.*\\w+'))[1]
--get 5th separate blocks splitted by10+ dashes, regex for splitter
(regexp_split_to_array(des,E'\\-{10,}'))[5]
reverse:
https://wiki.postgresql.org/wiki/Reverse_string(supports only above 8.3)
data type:
http://www.postgresql.org/docs/9.3/static/datatype.html
string:
http://www.postgresql.org/docs/9.1/static/functions-string.html
operator:
http://www.postgresql.org/docs/6.3/static/c09.htm
vacuum space:
Vacuum city_table
Function:
call:
select run_proc()
define:
CREATE OR REPLACE FUNCTION run_proc() RETURNS void AS $func$
DECLARE
func_body text;
BEGIN
func_body := '
update descr d
set formatted_city=city
from loc c
where c.state=d.state' ;
EXECUTE func_body;
END;
$func$ LANGUAGE plpgsql;
Function example:
--drop FUNCTION singular2plural(input text)
create FUNCTION singular2plural(input text) RETURNS text
LANGUAGE plpgsql IMMUTABLE STRICT AS $$
DECLARE
result text = '';
root text;
suffix text = '';
pluralres text = '';
VOWELS text = 'aeiou';
BEGIN
IF btrim(length(btrim(input)))=0 then
return input;
END IF;
IF length(regexp_replace(btrim(input), E'(\\w+\\s*)*','','g'))>0 then
RAISE EXCEPTION 'singular2plural contains invalid character';
END IF;
SELECT plural INTO pluralres
FROM aa_aberrant_plural_map
WHERE singular = $1;
if pluralres<>'' then
return pluralres;
end if;
root = input;
if substring(input,length(input)) = 'y' AND strpos(VOWELS,substring(input,length(input)-1,1))=0 then
root = substring(input,1,length(input)-1);
suffix = 'ies';
elsif substring(input,length(input)) = 's' then
if strpos(VOWELS,substring(input,length(input)-2,1))>0 then
if substring(input,length(input)-3)='ius' then
root = substring(input,1,length(input)-2);
suffix = 'i';
else
root = substring(input,1,length(input)-1);
suffix = 'ses';
end if;
else
suffix = 'es';
end if;
elsif substring(input,length(input)-1)='ch' or substring(input,length(input)-1)='sh' then
suffix = 'es';
else suffix = 's';
end if;
result = root||suffix;
RETURN result;
END$$;
Function example:
drop FUNCTION if exists aa_sp_cat();
CREATE FUNCTION aa_sp_cat() RETURNS void AS $$
update q set city='New York' from cities c where cityid=5;
$$ LANGUAGE SQL;
Table options:
Create table products
(
productid integer,
desc varying_character
) with (Appendonly=true, compresslevel=5, orientation=column)
Distributed by (productid);
appendonly=can only insert records, no delete/update
orientation=separate table by columns
partition=separate table into bulks of rows
Distributed=physical storage key
productid integer,
desc varying_character
) with (Appendonly=true, compresslevel=5, orientation=column)
Distributed by (productid);
appendonly=can only insert records, no delete/update
orientation=separate table by columns
partition=separate table into bulks of rows
Distributed=physical storage key
Impot data from file using psql:
create table city_table
(
city character varying(100)
,stateabbr character varying(10)
)
1. Start psql with the following command: psql.exe -h 10.10.10.10 -d databasename
2. CTP_4M-> \copy public.city_table from C:\city.csv with csv header quote as '"'
in city.csv, column names: city, stateabbr
Thursday, March 5, 2015
HTTP POST简介
在研究postmates的API时候https://postmates.com/developer/docs要知道怎么用POST来得到数据
基本URL为https://api.postmates.com/v1/customers/:customer_id/delivery_quotes
API key和customer id从这里可以得到https://postmates.com/developer/testing
所以URL为https://api.postmates.com/v1/customers/cus_KEX15lMKh_770k/delivery_quotes
postmates提到
"Authentication is specified with HTTP Basic Authentication
POST data should be encoded as standard application/x-www-form-urlencoded
The Postmates API requires authentication by HTTP Basic Auth headers. Your API key should be included as the username. The password should be left empty."
Authorization(request header):
Basic access authentication(http://en.wikipedia.org/wiki/Basic_access_authentication)提到client side要a string "username:password"且用Base64加密后在前加上Basic+空格
d067ca26-7eb8-4dab-bebf-30ba3601e0f2:结果是
Authorization: Basic ZDA2N2NhMjYtN2ViOC00ZGFiLWJlYmYtMzBiYTM2MDFlMGYyOg==
Post data:
由上述理论提到post data要用form-urlencoded形式
在request header中加入
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
这个content type也决定了request body用http get的parameter形式name1=value1&name2=value2而不是json形式
request body:
pickup_address=165 Broadway, New York, NY&dropoff_address=2 gold st, New York, NY
在fiddler显示最后的结果为
返回结果:
基本URL为https://api.postmates.com/v1/customers/:customer_id/delivery_quotes
API key和customer id从这里可以得到https://postmates.com/developer/testing
所以URL为https://api.postmates.com/v1/customers/cus_KEX15lMKh_770k/delivery_quotes
postmates提到
"Authentication is specified with HTTP Basic Authentication
POST data should be encoded as standard application/x-www-form-urlencoded
The Postmates API requires authentication by HTTP Basic Auth headers. Your API key should be included as the username. The password should be left empty."
Authorization(request header):
Basic access authentication(http://en.wikipedia.org/wiki/Basic_access_authentication)提到client side要a string "username:password"且用Base64加密后在前加上Basic+空格
d067ca26-7eb8-4dab-bebf-30ba3601e0f2:结果是
Authorization: Basic ZDA2N2NhMjYtN2ViOC00ZGFiLWJlYmYtMzBiYTM2MDFlMGYyOg==
Post data:
由上述理论提到post data要用form-urlencoded形式
在request header中加入
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
这个content type也决定了request body用http get的parameter形式name1=value1&name2=value2而不是json形式
request body:
pickup_address=165 Broadway, New York, NY&dropoff_address=2 gold st, New York, NY
在fiddler显示最后的结果为
返回结果:
Thursday, February 5, 2015
用Fiddler捕捉phone的traffic
具体细节参看官网:http://docs.telerik.com/fiddler/Configure-Fiddler/Tasks/ConfigureForiOS
1. phone & 电脑连接同一个wifi
2. 获取电脑的IP地址, 并且输入到phone的wifi设置中,port 8888是fiddler默认的。

3. 在Fiddler中设置options->connections->Allow remote computers to connect以及安装Certificate Maker plugin。
4. 在Fiddler中设置options->HTTPS->Actions->Trust root certificate
5. iphone6以上还需要信任证书Settings -> General -> About -> Certificate Trust Settings。登录手机 浏览器,输入地址192.168.1.3:8888。如果看见Fiddler Echo Service说明成功。
6. 可选项:fiddler中设置或者HTTPS
此时我们可以见到fiddler开始捕捉手机上的traffic,当然电脑上的traffic也会捕捉,process可以区分出他们,chrome是来自电脑,空白的是来自phone
7. 如上图所示,有的traffic会显示tunnel to,表示这些request用了SSL,我们在手机安装一些证书来骗过这些网站从而获得细节
电脑中fiddler的网址是http://localhost:8888/ 证书也位于这里
在手机我们输入电脑的IP,port是8888,就可以访问该网址,如上述例子,我们在手机浏览器输入http://192.168.1.3:8888/ 我们见到一个hyperlink: you can download the Fiddler certificate
安装了之后,就可以看到这些traffic了,不过不是所有SSL都可以骗,比如twitter就不可以了。
要删除fiddler cert可以settting->general->profile(iphone)
重新安装Fiddler的话都要重新再手机上安装此证书,在iphone中,证书通过以上方法可能打开不了,可以在fiddler把证书下载下来Options->HTTPS->Actions->Export root cert to desktop然后通过邮件发到手机即可打开。
Android的配置:
http://docs.telerik.com/fiddler/Configure-Fiddler/Tasks/ConfigureForAndroid
另一个Post
1. phone & 电脑连接同一个wifi
2. 获取电脑的IP地址, 并且输入到phone的wifi设置中,port 8888是fiddler默认的。
3. 在Fiddler中设置options->connections->Allow remote computers to connect以及安装Certificate Maker plugin。
4. 在Fiddler中设置options->HTTPS->Actions->Trust root certificate
5. iphone6以上还需要信任证书Settings -> General -> About -> Certificate Trust Settings。登录手机 浏览器,输入地址192.168.1.3:8888。如果看见Fiddler Echo Service说明成功。
6. 可选项:fiddler中设置或者HTTPS
此时我们可以见到fiddler开始捕捉手机上的traffic,当然电脑上的traffic也会捕捉,process可以区分出他们,chrome是来自电脑,空白的是来自phone
7. 如上图所示,有的traffic会显示tunnel to,表示这些request用了SSL,我们在手机安装一些证书来骗过这些网站从而获得细节
电脑中fiddler的网址是http://localhost:8888/ 证书也位于这里
在手机我们输入电脑的IP,port是8888,就可以访问该网址,如上述例子,我们在手机浏览器输入http://192.168.1.3:8888/ 我们见到一个hyperlink: you can download the Fiddler certificate
安装了之后,就可以看到这些traffic了,不过不是所有SSL都可以骗,比如twitter就不可以了。
要删除fiddler cert可以settting->general->profile(iphone)
重新安装Fiddler的话都要重新再手机上安装此证书,在iphone中,证书通过以上方法可能打开不了,可以在fiddler把证书下载下来Options->HTTPS->Actions->Export root cert to desktop然后通过邮件发到手机即可打开。
Android的配置:
http://docs.telerik.com/fiddler/Configure-Fiddler/Tasks/ConfigureForAndroid
另一个Post
Monday, February 2, 2015
Selenium in C# - Browser Automation
OpenQA.Selenium:
Start: http://docs.seleniumhq.org/docs/03_webdriver.jsp
SetPreference: http://seleniumeasy.com/selenium-tutorials/firefox-profile-preferences-using-selenium-webdriver
FindElement(By): http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/By.html?_sm_au_=iVVsMF35HZfF7QWj
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("network.proxy.http", "1234");
FirefoxDriver browser = new FirefoxDriver(profile);
browser.PageSource.Contains("abcd");
IWebElement total = browser.FindElement(By.ClassName("ddd"));//css class
String totalStr = total.Text;
ReadOnlyCollection<IWebElement> children = total.FindElements(By.ClassName("eee")).FindElement(By.ClassName("fff"));
foreach (IWebElement product in children){}
String innerHtml = total.GetAttribute("innerHTML");
total.Click();
//selelium's approach: scroll an element into view
browser.ExecuteJavaScript("arguments[0].scrollIntoView(true);", total);
xpath
("//div[@class='abc']")[1]
("//div[contains(@class, 'abc']")//h4[contains(text(), 'bb')]
Start: http://docs.seleniumhq.org/docs/03_webdriver.jsp
SetPreference: http://seleniumeasy.com/selenium-tutorials/firefox-profile-preferences-using-selenium-webdriver
FindElement(By): http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/By.html?_sm_au_=iVVsMF35HZfF7QWj
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("network.proxy.http", "1234");
FirefoxDriver browser = new FirefoxDriver(profile);
browser.PageSource.Contains("abcd");
IWebElement total = browser.FindElement(By.ClassName("ddd"));//css class
String totalStr = total.Text;
ReadOnlyCollection<IWebElement> children = total.FindElements(By.ClassName("eee")).FindElement(By.ClassName("fff"));
foreach (IWebElement product in children){}
String innerHtml = total.GetAttribute("innerHTML");
total.Click();
//selelium's approach: scroll an element into view
browser.ExecuteJavaScript("arguments[0].scrollIntoView(true);", total);
xpath
("//div[@class='abc']")[1]
("//div[contains(@class, 'abc']")//h4[contains(text(), 'bb')]
KB: C#
AppSettingsReader:
Read app.config file
XmlDocument & XmlNode (Read XML file):
XmlDocument configDoc = new XmlDocument();
configDoc.Load(fileName);
XmlNode oneNode = configDoc.SelectSingleNode("//config/");
String abc = botNode.Attributes["proxy"];
Attribute & CustomAttributeData:
FieldInfo[] fs = obj.GetType().GetFields();
foreach (FieldInfo f in fs)
{
IList<CustomAttributeData> attributes = CustomAttributeData.GetCustomAttributes(f);
foreach (CustomAttributeData attribute in attributes)
{
//check if the field was marked as [ConfigValue]
if (attribute.Constructor.DeclaringType.Equals(typeof(ConfigValue)))
{}
}
}
[AttributeUsage(AttributeTargets.Field)]
public class ConfigValue : Attribute
{
private String prameName;
public ConfigValue(String name)
{
prameName = name;
}
}
[AttributeUsage(AttributeTargets.Field)]
public class RegexFile : Attribute
{
private String fileName;
public RegexFile(String name)
{
fileName = name;
}
}
Use:
[ConfigValue]
String proxy;
[RegexFile("rabc.regex")]
private Regex rabc;
Read app.config file
XmlDocument & XmlNode (Read XML file):
XmlDocument configDoc = new XmlDocument();
configDoc.Load(fileName);
XmlNode oneNode = configDoc.SelectSingleNode("//config/");
String abc = botNode.Attributes["proxy"];
Attribute & CustomAttributeData:
FieldInfo[] fs = obj.GetType().GetFields();
foreach (FieldInfo f in fs)
{
IList<CustomAttributeData> attributes = CustomAttributeData.GetCustomAttributes(f);
foreach (CustomAttributeData attribute in attributes)
{
//check if the field was marked as [ConfigValue]
if (attribute.Constructor.DeclaringType.Equals(typeof(ConfigValue)))
{}
}
}
[AttributeUsage(AttributeTargets.Field)]
public class ConfigValue : Attribute
{
private String prameName;
public ConfigValue(String name)
{
prameName = name;
}
}
[AttributeUsage(AttributeTargets.Field)]
public class RegexFile : Attribute
{
private String fileName;
public RegexFile(String name)
{
fileName = name;
}
}
Use:
[ConfigValue]
String proxy;
[RegexFile("rabc.regex")]
private Regex rabc;
Subscribe to:
Posts (Atom)