DataAdapter.UpdateCommand, InsertCommand, DeleteCommand will be used to update the DB as well by just DataAdapter and Command without CommandBuilder, see example. //Use CommandBuilder to update the DB with DataAdapter.
>>DataRow:(>>Data Row)
*Child DataRow:(>>Child DataRow)
---->>Get Child DataRows----(>>Get child data rows)
[ASP.Net]
DataRow ParentDR=DS.Tables["Table1"].Rows.Find("12");//12 is the authoer ID(>>Find DataRow>>Find Data Row>>Find DataTable rows)
DaraRow[] ChildDR=ParentDR.GetChildRows("RelationName");
//DS has been set the DataRelation with "RelationName".ChildDR are the datarow got by parentrow with relation name.
*Add DataRow:(>>Add DataRow>>Add Data Row>>Add row data>>Add new row data)
[ASP.Net]
DataRow DR=DataTable.NewRow();//>>Add new row by DataTable
[JS] (>>Add JS row>>Add Javascript row>>Insert JS row>>Insert javascript row)
var oTr=document.getElementById("TableID").insertRow(2); //Insert a new row at index 2(index begin as 0), it means insert the row as the third row
*Delete DataRow:(>>Delete DataRow>>Delete Data Row>>Delete Row>>Remove datarow)
[ASP.Net]
1.DataRowCollection.Remove(DataRow row);//Delete actually, see example:
2.DataRow.Delete();//Mark as deleted, not deleted actually.If you want to delete it actually, do following:
public void AcceptChanges(); //Deleted after that, or RejectChanges() to undo.(>>Accept Change)
*Find data row:(>>Find datarow>>Find data row)
[ASP.Net]
DataRowCollection DRC=DataSet.Tables[0].Rows;//>>Data row collection>>DataRow Collection
DataRow DR=null;
DR=DRC.Find("PrimaryKeyText");
//Tables[0] has been set the primary,search for the info by Set Primary key,you can use "PrimaryKeyText" to find out the related row.
>>Data:
*Order data:(>>Order data>>Sort Data)
[ASP.Net]
{DataTable}
http://jims57.blog.163.com/blog/static/951361720103775819918/ //>>Order data by DataTable>>DataRow
{DataView}(>>DV sort data>>DataView Sort data)
DataView.Sort="BookAuthor";//Sort by book author. Or .Sort="BookAuthor asc"
>>Primary key:
*Set Primary key:(>>Set primary key)
[ASP.Net]
1.
DataColumn[] dc=new DataColumn[1];//>>New data columns>>New DataColumns
dc[0]=DataSet.Tables[0].Columns[0];
DataSet.Tables[0].PrimaryKey=dc;//>>Data Column>>Set datatable primarykey>>Set DataTable primary key
>>Address:
*IP Address:(>>IP Address)
---->>Get user ip address----(>>Get client address>>Get client IP address>>Get user host address>>User host address)
[ASP.Net]
Request.UserHostAddress;//return string.
>>Inherit:
*Inherit father method:(>>Inherit father method>>Inherited method>>Inherited class)
[ASP.Net]
base.FatherMethod("Value");//base means the father class, "FatherMethod" is a method name in father class.
>>Pass Value(>>Out>>Ref>>Out and Ref>>Ref and out)
*Difference between Out and Ref(>>Difference between Out and Ref>>Out values):
(1).out在进入函数前,可以不赋值,但ref一定要赋值进入函数;
(2).out在退出函数时,一定有值被赋于,而ref可赋也可以不赋值。
(3.)Ref will change the original value.
----Example 1----(>>out parameters>>ref parameters>>Out example>>Ref example)
http://jims57.blog.163.com/blog/static/9513617200910110364899/edit/?mode=prev
>>Host:
*Host name:
---->>Get Host name----
[ASP.Net]
HttpContext.Current.Request.Url.Host; //>>HttpContext>>HttpContext host name>>Get current pc IP address>>Get current PC host name
>>Server:
*Server string:(>>Server string>>Server connection string>>Connection string)
---->>Set Server connection string----(>>Set connection string)
[Asp.Net]
{Web.Config}
http://jims57.blog.163.com/blog/static/9513617201035113536314/
{C#}
SqlConnection.ConnectionString=ConnectionString;//ConnectionString will be set in web.config.
---->>Get Server Connection string----(>>Get connection string)
[Asp.Net]
1.{Get from Web.config}
Way 1:
System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionName"].ToString();
Way 2:
Example.
2.{>>Get server connection string by SqlDataSource}
>>Ajax:(>>Asynchronization)
*How to asynchronize:(>>How to asynchronize>>How to do asynchronization)
----Steps----(>>Create Async object steps>>Asynchronization steps)
1.Create Async object(You have to check which browser is using, and then create the related XMLHttpRequest object), like Example 1.
2.Open the server.aspx page, like "AsyncObj.open("GET","Server.aspx",true);".
3.Set the property, onreadystatechange, see Exmaple 1.
4.Send request by "AsyncObj.send(null);"
5.Get the response from server by "AsyncObj.responseText" after sending the request in Step 4.
----Summary----(>>Asynchronization Summary>>Ajax Summary>>XMLHttpRequest Summary)
1.innerHTML have to use upperCase to show, like "document.getElementById("MyID").innerHTML=XMLRequest.responseText; , see Example 1.
2.Attention to the case-sensitive about both "AcyncObj=new ActiveXObject("Microsoft.XMLHTTP")" and "AcyncObj=new XMLHttpRequest();".The
HTTP in Microsoft.XMLHTTP is uppercase, but Http in XMLHttpRequest is not all uppercase.
3. "GET" and "POST" have to be upper case, like "AcyncObj.open("GET","Server.aspx",true);"
4. When "GET", use "AcyncObj.send(null);"(use "null") to send, if "POST" you have to add the HttpHeader like this "AsyncObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");" (>>Async object header>>Post request header>>Post header)
5.Server.aspx HTML should be deleted, for the responseText will include all the html the server.aspx has,just use it like this.
6.If you have the Server Control, you have to use "onClientClick" to use the js, like this. (>>Use JS functions>>How to use js functions>>How to use javascript functions>>Use Javascript functions)
7.If you want to do asynchronization, you'd better use <input> not <ASP:Button> to do the async, for the <ASP:Button> has the problem when doing the asynchronization.
8.[JQuery]: If you use load(url,[data],[callback]) to get the async data, use "GET" to request when without data, if data is involved in the request, it is "POST", if you have to use "GET" to request and want the [data] as well, you should use "?ID=12" format to finish.
----Example----
[Ajax] (>>How to use Ajax>>How to use XMLHttpRequest)
Example 1. (>>Use async object)
[JQuery] (>>How to use JQuery Ajax>>JQuery Ajax)
----Info----
Info 1. (From Jacob)
----Example----
Example 2. (>>Get async data by JQuery)
*Ajax Composition:(>>Ajax Composition>>Ajax Objects)
Javascript,Css,DOM, XMLHttpRequest
*About XMLHttpRequest:(>>About XMLHttpRequest>>About Async object>>About asynchronous object)
----Create XMLHttpRequest Object----(>>Create HttpXMLRequest Object>>Create Async object>>Create Asynchronous object)
http://blog.163.com/jims57/blog/static/9513617201032101425683
*XMLHttpRequest ReadyState:(>>XMLHttpRequest ReadyState>>ReadyState>>XMLHttpRequest State>>Check XMLHttpRequest State>>Check State)
http://jims57.blog.163.com/blog/static/951361720103395417467/
*Send XMLHttpRequest Request::(>>Send XMLHttpRequest Request>>Send Request to server>>Create request>>Set up request>>send async request)
XMLHttpRequest.Open("GET","Page.Aspx",true);//Method={GET,POST}
----Example----(>>Send async request)
Example 1. (>>Send Async Request by GET)
>>Socket:
*How to use Socket:(>>How to use socket)
----Example----(>>Socket Examples)
Example 1.
Example 2.//Good example even some format errors.
*Set up Socket:(>>Set up socket>>Establish socket>>New UDP socket>>New Socket>>Create socket object)
[For Udp]
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //>>Udp>>AddressFamily>>Socket Type>>SocketType
[For Tcp]
Socket S = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
>>Constant:
*How to use constant:(>>Constant)
[C#]
public const int port = 11000;//>>C# constant>>Define C# Constant>>Define Constant
>>Chat:
*Send and receive message:(>>Send Message>>Receive message)
http://jims57.blog.163.com/blog/static/95136172010325144940/
>>GUID:
*GUID type:(>>GUID Type)
SqlParameter.SqlDbType=SqlDbType.Guid;>>SqlDbType>>DB Type>>Sql DB Type
>>Certificat:(>>Security)
*SSL Certificate:(>>SSL Certificate>>Get SSL Certificate>>Get Security certificate>>Get Certificate>>Get SSL Security certificate)
[VeriSign](>>VeriSign)
----Link----
http://www.Verisign.com
----Info----
《ASP.Net 2.0电子商务开发实践》 P.367
>>HyperLink:
*How to use Hyperlink:(>>How to use Hyperlink)
[ASP.Net]
<Asp:HyperLink runat="server" ID="ID" NavigateUrl="~/Register.aspx" Text="ClickMeText" ToolTip="Go register page" CssClass="UserInfoLinkCss"/> //>>Relative path>>ToolTip>>CssClass>>Navigate Url
>>User:
*Create User:(>>Create user)
[ASP.Net]
{Membership}(>>Create user by membership)
MembershipUser user=Membership.CreateUser("UserName","PWD","Email","QuestionToGetBackPassword","Answer",true,out status);//true=Allow user to login,status=return status of user
>>User Controls:
*How to use User Controls:(>>How to use User Controls)
http://jims57.blog.163.com/blog/static/951361720103111450442/
>>List:
*How to use List:(>>How to use List)
----Example----
Example 1. (>>New List)
Example 2.
Example 3. (>>Add list items)
>>Password:
*Set Password rules:(>>Set password rules>>web.config password format>>Password rules>>Set password format)
[ASP.Net]
Set in ASPNetSqlMembershipProvider in machine.config or web.config
>>Membership:
*How to use Membership:(>>How to use Membership)
----Step----(>>Use membership steps)
1.Create Table scheme by aspnet_regsql.exe automatically.(C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727)
2.Setting for MemberShipProvider and RoleManagerProvider,like this.(>>Set Membersip in web.config)
3.Write coding by membership and MembershipUser, like this.
*Membership Database:(>>Membership database>>Membership DB)
---->>Create membership db----(>>Create membership database)
1.Create the related DB table by aspnet_regsql.exe.(C:/WINDOWS/Microsoft.NET/Framework/v2.0.50727)
---->>Combine membership database into existing DB----(>>Combine membership DB to existing DB>>Combine DB>>Combine membership database):
a.Run "Visual Studio 2008 Command" from start button.
b.Type "aspnet_regsql.exe".
Reference:<<亮剑.Net ASP.NET商业级数据库网站开发实践>> P.331
*MemberShip namespace:(>>Membership namespace)
[ASP.Net]
System.Web.Security.MemberShip;
*Get User ID by MemberShip:(>>Get User ID by membership>>Get UserID by memebership)
MemberShip.GetUser(HttpContext.Current.User.Identity.Name).ProviderUserKey; //>>HttpContext>>Get Current user object>>GetUser>>Get user>>Identity
>>Profiles:(>>User Info)
*Set Profiles:(>>Set Profile>>Set user info)
[ASP.Net]
http://jims57.blog.163.com/blog/static/9513617201023111112811/ //>>Get User>>MemberShip get user>>HttpContext.Current>>Get Current HttpContext
>>SqlDataSource:
*Set SqlDataSource:(>>Set SqlDataSource)
<Asp:SqlDataSource ID="ID" runat="server" ConnectionString="<%$ConnectionStrings:BallonShopConnection%>" SelectCommand="Select [ID],[Name] from [Table1]"/>
//ConnectionString:BallonShopConnection is set in Web.Config //SqlDataSource Connection string>>Set Connection String>>Set Connectionstring>>Select Command
>>Roles:
*Add roles:(>>Add roles)
[ASP.Net]
{CreateUserWizard}
http://jims57.blog.163.com/blog/static/95136172010230112438123/ //>>Sender as>>Get sender>>CreateUserWizard
----Remark----
You can add the new role manually by tool named "Web Site Administrator Tool" provided by ASP.Net.
>>Encrypt:(>>Encryption>>MD5>>SHA1>>DES>>3DES)
*How to Hash password:(>>How to encrypt>>Encrypt password>>Hash Password>>Hash String>>How to hash password)
[SHA1]
http://jims57.blog.163.com/blog/static/95136172010229115624546/ //>>ToBase64String>>To SHA1 string
[DES]
http://jims57.blog.163.com/blog/static/95136172010591461411/
*Encrypt and Decrypt:(>>How to encrypt and decrypt string>>Encrypt string>>Decrypt data>>Encrypt data>>Decrypt string)
http://jims57.blog.163.com/blog/static/95136172010230104316110/ //>>Get byte from string>>ReadToEnd>>Flush datatrin
>>Load:(>>PreRender>>Init)
*Load Summary:(>>Load Summary>>PreRender Summary)
[ASP.Net]
PreRender: Load before load method
>>Session:
*Session Data:(>>Session Data)
---->>Set Session data----
[ASP.Net]
Session.Add("key1","value1");
---->>Get session data----
[ASP.Net]
Session.Contents["key1"];
*Get session:(>>Get Sessions)
[ASP.Net]
{HttpContext}//>>HttpContext>>Get HttpContext Session:
HttpContext Context=HttpContext.Current;
object Session=Context.Session["CartID"];
>>DropDownList:(>>DDL)
*How to use DDL:(>>How to use DDL>>How to use dropdownlist)
----Summary----(>>DDL Summary>>DropDownList summary)
1.When binding the data to DDL, it won't triger the event SelectedIndexChanged(object sender,EventArgs e), like this.(>>Bind data to ddl>>DDL select event>>DDL select change event)
*Add item to DropDownList:(>>Add item to dropdownlist)
DropDownList.Items.Add(new ListItem(ItemName,ItemValue)); //>>ListItems>>List Items>>Add List Items to DropDownList>>New dropdownlist item
>>Upload:
*Upload files:(>>Upload Files)
[ASP.Net]
http://jims57.blog.163.com/blog/static/951361720102260118106/ //>>Server.MapPath>>Relative Path>>Map Path>>Upload control
>>Escape():
*Escape Method:(>>Escape method)
[JS](>>JS Escape method>>JS Escape() method)
---->>JS Escape example----
Example 1
>>Escape Characters:
[C#]
http://jims57.blog.163.com/blog/static/95136172010361133763/
[ASP.Net]
& & //>>&
>>Color:
*Good color:(>>Good colors)
---->>My collection color----
*System Color:(>>System Color)
[.Net]
System.Drawing.Color.Red;
>>User name:(>>Username)
*Get username:(>>Get UserName>>Get user name)
[Asp.Net]
{>>Get Username by HttpContext} (>>Get user name by HttpContext)
string M_StrUserName=HttpContext.Current.User.Identity.Name;//>>HttpContext>>HttpContext User name>>HttpContext Username
>>Authentication:(>>Authenticated)
*Windows Authentication:(>>Windows Authentication)
---->>How to use Windows Authentication----
----Info----
Info 1.
(>>Get windows user name>>Get windows logon user name>>Get windows logon name>>Identity Impersonate>><Identity Impersonate>>Impersonate)
*Authenticated User:(>>Authenticated User>>Logined user)
----Name Space----(>>Authenticated user namespace>>>>Current user namespace>>user namespace>>Logined user namespace)
System.Web.HttpContext.Current.User.Identity.Name;
*How to use Authentication:(>>How to use authentication>>How to use Web.Config Authentication)
----Summary----(>>Authentication Summary)
1.IIS priority is higher than web.config, if you set user can access a specific page in web.config, but IIS setting is deny, system will follow IIS settings, like
this(These part with blue background).
2.If you set <identity impersonate="true">, it will show the name the IIS set, like this.
----Info----
Info 1.
*Forms Authentication NameSpace:(>>Forms Authentication Namespace>>Form Authentication Namespace)
using System.Web.Security;
*Mixing Authentication:(>>Mixing Authentication>>windows and form authentication>>Windows and Forms Authentication)
[.Net] (>>.Net Mixing Authentication)
----Summary----
<For WinLogin.aspx> //WinLogin.aspx means the page which is used to check the Windows Authentication.
1.Disable anonymous user for WinLogin.aspx at IIS.
2.Set the Integrated Windows Authentication. 1 and 2, see this. (>>Set windows authentication)
----Info----
Info 1.
(>>Get login Name>>Get Server login name>>get server variable>>Get logon user name>>Get logined user name>>Get login User name>>Server variable>>Get server login name)
*Validate user login:(>>Validate user login>>Validate login>>Authenticate login>>Authenticate user login>>Form validation)
[ASP.Net]
----Forms Authentication---- (>>Form login>>Form Authentication>>Forms Login>>Forms Authentication)
----Example----(>>Forms Authentication Examples>>FormAuthentication>>Form Authentication>>Sign Out>>Redirect to login page>>Set login>>Check login>>Save login info to client>>Save login info to cookie>>How to use Forms Authentication)
Example 1
My Example 2.(>>Sign out form authentication)
----Step----(>>Forms Authentication Steps)
1.Set redirect policy and user authorization in Web.config file, like this.(>>Web.config for Forms Authentication>>Settings for Forms Authentication)
2.Write the login code for Form Authentication, like this.(>>Forms Authentication Login>>login Forms Authentication)
*Check Authentication:(>>Check Authentication>>Check if authenticated)
[ASP.Net]
if(HttpContext.Current.User.Identity.IsAuthenticated) //>>HttpContext>>Cureent HttpContext>>Identity>>User Authentication>>Check user login
{
///TODO;
}
*Set Admin Right:(>>Set Admin Right>>Set administrator right)
[>>Form Authentication]
http://jims57.blog.163.com/blog/static/9513617201021742047318/
>>Performance:
*Improve performance:(>>Improve performance>>Improve system speed>>Improve Website speed)
---->>Way to improve performance----
[ASP.Net]
1.IsPostBack:
if(!Page.IsPostBack)//The way is used to improve it, for the page won't reload when post back.
{
////TODO;
}
2.Output Cache:(>>Output Page Cache>>Output Cache)
<%@OutputCache Duration="1000" VaryByParam="VariablesName"%> //Duration unit is second,VaryByParam means change the cache by incoming variables.
[SQL Server]
1.Do not use * when select.
>>Soundex(>>Alike Words):
*How to use soundex:(>>Get the like words>>Search for alike words>>Search for like word>>Find alike words)
[SQL]
Select @soundWord=soundex(@Word);//The soundex will search for those words which is the same by pronunciation, the method is not very fast.
>>Validate:(>>Validation)
*Input validatation:(>>Validate input content>>Input validation>>Validation control>>Control validation>>Validate control)
[ASP.Net]
1.<asp:requiredfieldvalidator id="LogonNameRequiredFieldValidator" runat="server" controlToValidate="LogonNameTextBox"
errormessage="用户名必须填写 " display="Dynamic">*</asp:requiredfieldvalidator>
2. <asp:validationsummary id="LogonValidationSummary" runat="server" HeaderText="请正确填写您的用户名及密码"></asp:validationsummary>
//>>Validation summary
*Button Validation:(>>Button Validation>>Validate by Button>>Button Validation Event)
[ASP.Net]
<Asp:Button ID="Button" runat="server" CausesValidation="true" CommandName="Update" Text="Update"/> //>>Button Event>>Button Command
>>Page:
*Page Event:(>>Page Event>>Paging Event)
---->>Change page index event----(>>Change page event)
[ASP.Net]
----ASPxGridView----(>>ASPxGridView change page event>>ASPxGridView page event)
Example 1.
*Redirect Page:(>>Redirect page)
[JS](>>JS redirect page>>Javascript redirect page)
----Example----
My Example 1.
*Validate Page:(>>Validate page>>Page validation>>Valid Page)
if(Page.IsValid)
{
////TODO;
}
*Get current page:(>>Get current page path>>Get page current path)
[ASP.Net]
string M_StrPage=Request.AppRelativeCurrentExecutionFilePath; //Return string format as "~/Index.aspx" >>Get relative path>>Request>>Get path
if(String.Compare(M_StrPage,"~/Index.aspx",true)==0) //true means the comparation ignore the case-sensitive. (>>Compare string>>Get root path>>Root Path)
{
////TODO;
}
>>Script Manger:(>>Scripmanager>>Page.ClientScript>>Set Script)
*How to use Script Manager:(>>How to use script manager)
[ASP.Net]
http://jims57.blog.163.com/blog/static/951361720102171943323/
*Tie the TextBox to Button:(>>Tie TextBox to Button>>Link TextBox to Button>>Link Button>>TieButton>>Tie Button>>Link textbox and button)
http://jims57.blog.163.com/blog/static/9513617201021713621619/
>>Replace:
*How to use replace:(>>How to use replace)
[C#]
using System.Text.RegularExpressions; //You have refer to the namespace first.(>>Regex namespace)
string Str=" abck d d "";
Str=Regex.Replace(Str," ","*");//return like this. (>>How to use Regex Replace)
[SQL]
replace(@Sentence,@WordToBeReplace,@WordToReplace)//The method "Replace" is internal one so it is very very fast to perform.
>>NameValueCollection:
*How to use NameValueCollection:
http://jims57.blog.163.com/blog/static/9513617201021655959579/(Must add namespace using System.Collections.Specialized)
>>Encoding:
*Set the global encoding:(>>Global Encoding>>Set Global Encoding)
[Web.Config]
<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="en-us"/> //Set all the user in different time zone show the same encoding(same text format)
>>Eval:
*Eval Format:(>>Eval Format)
[ASP.Net]
<span><%#Eval("Price","{0:c}")%></span>
*Eval():(>>Eval method)
[JS](>>Javascript Eval()>>JS Eval())
---->>JS Eval Example----
alert("2+3");//return:"2+3"
alert(eval("2+3"));//return:5
----Summary----(>>Eval summary>>JS eval summary)
1.You can change the string into the JSON object directly, by "var p=eval("("+JSON_text+")")".
>>Alignment:
*How to use alignment:
[Html]
<td vAlign="top" width="250"></td> //(>>VAlign)
>>Bind Data:
*How to bind data to control:(>>Bind Control Data>>Bind data to control>>How to bind data to control>>Eval>>DataBind())
http://jims57.blog.163.com/blog/static/9513617201021644556549/edit/ (>>Bind dropdownlist data>>Bind DDL data>)
>>Request.QueryString:
*How to use Request.QueryString(>>How to use Request.QueryString>>Get Variables>>Get variables value>>Get Variable Value):
[ASP.Net]
1.string M_Str=Request.QueryString["Variables"];
2.Request.Form["TextBox1"];
>>Enumeration:(>>Enumeration)
*How to use Enumeration:(>>How to use enumeration)
http://jims57.blog.163.com/blog/static/951361720103605521308/
>>Struct:
*How to use struct:(>>How to use struct)
[C#]
http://blog.163.com/prevBlogPerma.do?host=jims57&srl=9513617201021631247169&mode=prev
>>Int32:
*Int32 Try:(>>Int32 Try>>Try Int32>>Int try>>Int32.TryParse)
http://jims57.blog.163.com/blog/static/951361720102293136122/
>>Type:
*Type Transferation:(>>Type Convert>>Convert Type>>Type Transferation>>TryParse)
[C#]
Int32.Parse(ConfigurationManager.AppSettings["MyID"]);//>>Configuration Manager>>ConfigurationManager
Decimal.Parse(AVaribles);
Byte.Parse(variable);//>>Bype.Parse
Double.Parse(DataRow["Name"].ToString()); >>DataRow>>Get DataRow value by name
IPAddress ipaddress = IPAddress.Parse("127.0.0.1"); //(>>Convert string into IP adress>>IPAddress>>IP address>>Convert to IP address>>Convert string to IP address)
Example 1.(>>Convert DNS to IP address>>DNS to IP address)
[JS]
iWeek=parseInt(prompt("Please input the number."));//>>Convert string to number
iNumber=Number(prompt("Please your number"));//>>Convert string to number
[SQL]
Str('123') //reutn 123 as int, convet string to int
Convert(CONVERT(data_type,expression[,style])) , see info.//(>>How to use sql convert)
cast(10.234 as int) //return 10.Cast means convert a type to into type, this example mean, converting "float type" to int. Format: cast(Field as SqlType)
CAST('2008-10-16 10:41:19' AS datetime) //return datetime from string format
*Type Summary:(>>Type Summary)
----Info----(>>Type Info)
Info1 (>>Int scope>>Bigint scope)
Info2
----Remark----(>>Type Remark)
1.Char will be better than VarChar, if you want the specific length of the characters
[SQL] (>>SQL Type>>SQL DBType>>SQL DB Type>>DBType.Ansistring)
---->>SQL Type----
DBType.AnsiString; //This type is used to transfer long variables, like product description. (DbType.String <=4000 Unicode chars)
---->>SQL Type Summary----(>>>>char and varchar)
1.Char(2): You can input 2 English letters or 1 Chinese l char.
2.NChar(2):2 English letters or 2 Chinese chars.
3.SmallInt(-32,768 - 32,767), TingInt(0-255)
>>Variable:
*Set Variables:(>>Set Variables)
[SQL]
Select @Word2=Replace(@Sentence,@WordToBeReplaced,@WordToReplace)
*Use variable in SQL(>>Use strored procedure variables>>Stored Procedure Variables):
[SQL 2008 Store Procedure]
http://jims57.blog.163.com/blog/static/95136172009101201832681/edit/?mode=prev
>>Null
*Set Null value:(>>Set null value)
[C#]
if(M_IntCtrlID2==null)
{
M_Params[1].Value =DBNull.Value;//>>Set DBNull value>>Set DB null value
}
*Check the null:(>>IsNull>>Check if Null)
[VB.Net]
If IsNull(RS("Email_addr")) Then
MsgBox "Email is Null"
End If
[SQL] (>>SQL Null>>Check SQL Null>>Check SQL DBNull)
select IsNull(Sum(Product.Price*ShoppingChart.Quantity),0) from ShoppingChar inner join Product on ShoppingCart.ProductID=Product.ProductID where ShoppingCart.CartID=@CartID//IsNull will covert Null into 0.
*Select Null:(>>Select Null by SQL>>Check sql null)
Select ID from table1 where ID=110 and Name is null //Must use "is null" to select null value Name field(If Name field is null value), can not use "select ID from table1 where ID=110 and Name=null" to get
>>Table:
Example 1.
Example 1 .(>>Row_Number()>>SQL Table variables>>Table Variables>>Create Tempory
Example 2. (Info1)
Practice 1 (>>Output SQL parameters>>Output SQL variables>>Create SQL temp table>>Create sql temporary table>>SQL mode>>SQL division>>Define SQL variables>>Set sql variables)
>>Ritht():(>>Left()>>Mid())
*Right, Left and Mid method
[C#]
http://jims57.blog.163.com/blog/static/9513617201021553341451/ (>>C# Right()>>C# Left()>>C# Mid())
>>Template Language:
*How to use template language Freemaker(For java):
http://freemarker.sourceforge.net/
>>HTML
*Inner Html:(>>InnerHtml>>Inner html)
---->>Get InnerHtml----
[JQuery|JS]
Example //(>>Set div innerhtml>>Get div innerhtml)
*Html Controls:(>>Html controls)
[Html]
{downdroplist}(>>html dropdownlist controls)
*Encode Html:(>>Encode Html>>HtmlEncode>>Html Encode)
1.string M_StrEncodedHtml=Server.HtmlEncode(M_StrWithHtml);
2.Server.UrlEncode("UrlString");//Encode url, like Default.aspx?name+Name
*Decode Html
*Convert ASP.net into HTML(>>Create HTML>>Convert ASP.net into HTML>>Convert ASP.net to HTML)
http://jims57.blog.163.com/blog/static/951361720102845554794/edit/
>>iFrame:
*How to use iFrame:
http://jims57.blog.163.com/blog/static/951361720102810939139/
>>Play by turns(>>AD Play by turns):
[Flash] (>>Flash Play by turns>>Flash AD play by turns>>Rotate Flash>>Rotated Flash)
https://docs.google.com/uc?id=0Bz23VoSTWyf3ZWU5OTIzMTAtZThjNC00ZmFmLWJiZWMtYzU2YjE5ODRlMmM5&export=download&hl=en (>>Provided by Jacob)
>>Alipay:
*How to use Alipay(>>How to use alipay>>Alipay class>>Alipay interface routine>>Alipay port):
http://jims57.blog.163.com/blog/static/9513617201012684945380/
>>Declare:
[SQL]
Declare SQL Table(>>Declare SQL Table>>Declare @table):
http://jims57.blog.163.com/blog/static/95136172009112951659109/edit/?mode=prev
>>Data:
*Import Data Problem:(>>Import Data Problem)
[SQL Server]
----Problem 1----(>>Import excel 2003 to SQL server>>Import Data from Excel into SQL Server)[Number can not import as text]
http://jims57.blog.163.com/blog/static/95136172009111663425836/edit/
>>While:
*While true format(>>While true format>>While(true)>>While loop):
While(true)
{
if(Validation==true)break;//It must has the break to exit the loop
}
>>HTTP:
*How to use Http Object:(>>How to use Http Object>>How to Use Http Class>>Use Http Object)
http://jims57.blog.163.com/blog/static/95136172009101911657507/edit/?mode=prev
---->>HttpObj Summary----(>>Http Object Summary>>Http Obj summary)
Summary1
*HTTP Class(>>HTTP Class>>HTTPObj Class>>Http Object):
----Class 1----
http://jims57.blog.163.com/blog/static/95136172009101311427660/edit/?mode=prev
>>DBManager(>>DB Common Class>>DB Class):
----Class 1----
http://jims57.blog.163.com/blog/static/951361720091013113935678/edit/?mode=prev
>>Switch:
*Switch format(>>Switch format):
----Example 1----
http://jims57.blog.163.com/blog/static/95136172009101311238484/edit/?mode=prev
>>Thread(>>Threading):
*Thread Join:(>>Thread Join>>Thread.Join())
ThreadA.Join();//The thread B will not execute until Thread A finish;
----Example----
*How to use Thread(>>How to use Thread>>Use Thread>>how to use threading):
[C#]
[Without Parameter Method](>>Use Thread without Parameter>>Create threading)
http://jims57.blog.163.com/blog/static/95136172009101433036741/edit/?mode=prev [Have been practised by me]
[With Parameter Method](>>Use Thread with Parameter)
http://jims57.blog.163.com/blog/static/95136172009101433222734/edit/?mode=prev [Do not practise it as well]
*Control Control across Threading(>>access between thread>>Across thread>>access controls across threads>>Control control across threading>>Access to control across threading>>Update Control by Threading>>thread across access>>across threads access>>across thread access)
----Summary----
For Exampl 2.
(1).
----My Example----
http://jims57.blog.163.com/blog/static/951361720102154335051/edit/
----Example----
Example 1.
Example 2.
Exampe 3
*Thread Method(>>Thread Method):
http://jims57.blog.163.com/blog/static/95136172009101484134928/edit/?mode=prev
*Thread Property(>>Thread Property>>Thread Properties):
http://jims57.blog.163.com/blog/static/9513617200910148429469/edit/?mode=prev
*Thread ThreadState Properties(>ThreadState Properties>>ThreadState Property>>Threading State>>Thread State):
http://jims57.blog.163.com/blog/static/95136172009101484353656/edit/?mode=prev
>>Delegate(>>Asynchronization>>Asynchronisation):
*Delegate Summary:(>>Delegate summary)
1.When multi-pointing to call the delegate, you MUST make sure all methods return type are void.
2.When multi-pointing to call the delegate, DO NOT use "Out" type argument list.
3.The methods the delegate is going to call can be the normal method or static method.
4.Delegate CAN NOT be derived by another class.(Delegate is Sealed)
*Create Delegate(>>Create Delegate>>Use Delegrate>>How to use delegate)
----Summary----(>>Delegate and event summary>>Delegate summary)
1.For delegate and event example(example4):
(1). Event and delegate have to the same reference, like "PlayGame" in 小张 class, and "PlayGameHandler" in this example 4
(2).Event definition, like "public event PlayGameHandler PlayGame" , have to be done in event activator, 小张 class.
(3).Event achievement, like "PlayGame(this,e)", have to be in a function,"protected virtual void onPlayGame(EventArgs e)"
(4).The delegate with Event, the instantiation of delegate will be transferred to Event,like "z.PlayGame+=new PlayGameHandler(w.扣钱);"
(5).If you want to use the event without += or -=, you have to use it in the same class, event the child class can not use it if the event definition is in father class(or abstract class), like this.
----Step----(>>Call one method by delegate)
代理三步曲:
a.生成自定义代理类:delegate int MyDelegate(string Name);//This sentence must be outside any of the class.(>>New delegate)
b.然后实例化代理类:MyDelegate d = new MyDelegate(MyClass.MyMethod);//Both the static class and instantiated object can be add here.return value must be the same as the function it will use.
c.最后通过实例对象调用方法:int ret = d(NameValue);
----Example 2----(>>Call many methods by delegate>>Multi-Point call methods by delegate>>Multi Point to call delegate>>Mulit-point to call delegate)
http://jims57.blog.163.com/blog/static/9513617201031063910872/
----Example 3----
http://jims57.blog.163.com/blog/static/9513617200992911646566/edit/?mode=prev
----Example 3-----
http://jims57.blog.163.com/blog/static/951361720099293850185/edit/?mode=prev
Example 4. //Good example about delegate (>>Delegate and Event)
Example 5 //(>>My Delegate and event examples>>how to use delegate and event)
Example 6.
My Example 7
My Example 8 (>>Mouse and cat example>>Mouse and cat delegate and event)
----FYI----
http://jims57.blog.163.com/blog/static/951361720099290557214/edit/?mode=prev
----Info----
>>SMS:
*Send Google SMS by Calendar(>>Google SMS>>Send SMS by Google>>Send Google SMS>>Send Google Calendar SMS):
http://jims57.blog.163.com/blog/static/95136172009817113242743/edit/?mode=prev
*SMS API:
[Fetion]
http://www.libfetion.cn/
>>ViewState:
*ViewState NameSpace(>>ViewState NameSpace)
using System.Web.UI.StateBag;// It use "Name-Value" way to save the Viewstate
*Decode ViewState:(>>Decode ViewSate)
----Way 1----
http://www.wilsondotnet.com/demos/viewstate.aspx //Use the website to decode
*ExtractViewState(>>Extract ViewState>>Get ViewState)
----Way 1----HoHof
http://jims57.blog.163.com/blog/static/95136172009816307998/edit/?mode=prev
----Way 2----
http://blog.163.com/jims57/blog/static/95136172009816273360
>>EventValidation:
*Get EventValidation(>>Get EventValidation>>Extract EventValidation):
----Way 1----
http://jims57.blog.163.com/blog/static/9513617201001311416356/edit/
http://blog.163.com/jims57/blog/static/95136172009816273360
>>Cookies:
*Disable Cookies:(>>Disable Cookies)
[ASP.Net]
http://jims57.blog.163.com/blog/static/9513617201022853242492/
*Get Cookies:(>>Get Cookies)
[ASP.Net]
{HttpContext}(>>Get HttpContext Cookies)
HttpContext.Request.Cookies["CartID"];
*Add Cookies:(>>Add Cookies)
http://jims57.blog.163.com/blog/static/9513617201022824617658/ //>>Set Cookies>>Set Session>>Add Session>>TimeSpan>>HttpContext>>Session>>Cookies>>Add DateTime
>>CookieContainer:
*Get CookieContainer(>>Get CookieContainer):
using System.IO;
using System.Net;
public static System.Net.CookieContainer GetCookieContainer(string logUrl, byte[] data)
{
HttpWebRequest request = HttpWebRequest.Create(logUrl) as HttpWebRequest;
request.AllowAutoRedirect = false;//禁止自动重定向
request.Method = "Post"; //使用post方法
request.ContentType = "application/x-www-form-urlencoded";//form提交时使用urlencode
request.ContentLength = data.Length;
request.CookieContainer = new CookieContainer();
Stream uploadStream = request.GetRequestStream();
uploadStream.Write(data, 0, data.Length);
uploadStream.Close();
HttpWebResponse resposne = request.GetResponse() as HttpWebResponse;
resposne.Close();
return request.CookieContainer;//反会获取的cookieContainer
}
>>ToolStripMenuItem(>>ContextMenu>>Context Menu):
*Create Context Menu dynamic(>>Create Context Menu>>Dynamic Create Context Menu>>Create ToolStripMenuItem):
----Way 1----
ToolStripMenuItem item = new ToolStripMenuItem("动态菜单Text" ,null,new System.EventHandler(this.DynMenuItem_Click),"menuItemName");
//Format is(Name,Text,Handler,ShoutCut)
----Way 2----
ToolStripMenuItem mItem;
mItem = new ToolStripMenuItem(ds.Tables["table_1"].Rows[i]["FMenuText"].ToString());
mItem.Name = ds.Tables["table_1"].Rows[i]["FMenuName"].ToString();
mItem.Text = ds.Tables["table_1"].Rows[i]["FMenuText"].ToString();
mMain.Items.Add(mItem);
----Way 3----(>>ToolStripMenuItem Event>>ToolStripMenuItem Handler)
1. private void Tmi_Click(object sender, EventArgs e)
{
string M_Str=((ToolStripMenuItem)sender).Tag.ToString();
MessageBox.Show("Current text is "+M_Str);
}
//Add a event
2.
DataTable M_DT = Biz.GroupManager.DBAccess.GetAllGroupInfoWhichHaveRightToControlSupportGroup(M_IntUserID);
foreach(DataRow M_Dtr in M_DT.Rows)
{
M_StrItemText = M_Dtr["Name"].ToString();
M_TmiItem = new ToolStripMenuItem(M_StrItemText,null,this.Tmi_Click);
M_TmiItem.Tag = M_Dtr["ID"].ToString();
this.TmiAssignToGroup.DropDownItems.Add(M_TmiItem);
}
//Add object and set the drop down list for a ToolStripMenuItem.
----Way 4----
private bool CreateChildTmis(ToolStripMenuItem M_TmiParentTmi,DataTable M_DT, string M_StrFieldNameForText, string M_StrFieldNameForTag,System.EventHandler M_EhdHandlerName)
{
//Variables
bool M_BlnIsSuccess = false;
try
{
int M_IntUserID = Biz.SupportManager.Entity.G_IntUserID;
ToolStripMenuItem M_TmiItem;
string M_StrItemText = string.Empty;
if (M_DT.Rows.Count == 0) return false;
foreach (DataRow M_Dtr in M_DT.Rows)
{
M_StrItemText = M_Dtr[M_StrFieldNameForText].ToString();
if (M_EhdHandlerName!=null)
{
M_TmiItem = new ToolStripMenuItem(M_StrItemText, null, M_EhdHandlerName);
}
else
{
M_TmiItem = new ToolStripMenuItem(M_StrItemText);
}
M_TmiItem.Tag = M_Dtr[M_StrFieldNameForTag].ToString();
M_TmiParentTmi.DropDownItems.Add(M_TmiItem);
}
M_BlnIsSuccess = true;
}
catch
{
M_BlnIsSuccess = false;
}
return M_BlnIsSuccess;
}
----Summay----(>>ToolStripMenuItem Summary>>Context Menu Summary)
//将菜单加到顶层菜单下。
topMenu.DropDownItems.Add(subMenu);
*ToolStripMenuItem Event:(>>ContextMenu Handler>>Context Menu event>>Add Context Menu Event>>Add Context Menu Handler>>ToolStripMenuItem Event):
----Add Handler----
1.subMenu.Click += new EventHandler(Tmi_Click);
2.M_TmiItem = new ToolStripMenuItem(M_StrItemText,null,this.Tmi_Click);
----Handler----(>>Tmi Tag>>ToolStripMenuItem Tag)
private void Tmi_Click(object sender, EventArgs e)
{
string M_Str = ((ToolStripMenuItem)sender).Tag.ToString();//>>Get Tmi Tag
ShowConfirmInfo("Are you sure to do the action?");
}
>>Group By:
*Group By Summary:(>>GroupBy Summary>>Group By Summary)
[SQL] (>>SQL Group by summary>>SQL Groupby Summary)
1. When group by "Case when",you should have the field "case when",like this.
2.Have to have the "Aggregate function", like this.//Aggregate function includes "AVG","Count","Sum" etc.
3.You can combine more than 1 field as a field to group by, like this.
4.When you group by more than 1 fields, all the field name which is grouped by have to be written in select sentence, like this.
*Group by many field(>>Group by many fields>>Group by multi fields):
----Example----(>>Group by many fields examples)
Example 1: select AccountID,Year(YearField),sum(Money) from table1 group by AccountID,Year(YearField)//It will group by AccoutID and YearField
Example 2. (>>Combine fields to group by>>Group by combined fields)
*Group by format:(>>Group by Format)
SELECT Customer,OrderDate,SUM(OrderPrice) FROM Orders GROUP BY Customer,OrderDate //The customer and OrderDate after Group by must must the field "Customer" and "OrderDate"
>>Substring:
*How to use substring:(>>Get sub string)
[SQL]
substring(str,x,y): 由<str>中的第x位置开始,选出接下去的y个字元。//X index begin as 1.Example: substring(Description,1,@DesLen), index begin as 1.
[C#] (>>C# Substring)
---->>How to use C# Substring()----
String.Substring(int index,int length)
index:Begin from 0
length: The length you want
----Example----
Example 1.
>>With As: (With as's performance is better and use temporary table, like "create table tablename" and "Declare @Tablename table", use it when possible.)
*How to use With As(>>How to use With As>>With As format>>How to use SQL with as):
[SQL] (>>SQL With As)
---->>With as Format----(>>SQL with as format)
With TempTable1 as (select * from table1) //TempTable1 is the temporary table created by With As (>>SQL temporary table)
, //Must add the comma here
TempTable2 as (select * from table2)
---->>With As Example----(>>SQL with as examples)
Example 1.
>>Duplicate Rows:
*Delete the duplicate rows in SQL(>>Delete Duplicate Rows):
[SQL server] (>>With as>>SQL With As)
With Temp as (select Row_Number() over(order by Name) as RN,* from tb_Test)
delete from Temp where Temp.RN in
(select a.RN from Temp a,Temp b where a.RN>b.RN and a.Name=b.Name)//Must use "With" to record a related, it can not use " (select * from table) temp" to delete the records.
[Oracle]
delete from T where rowid in
(select a.rowid from T a,T b where a.rowid>b.rowid and a.id=b.id)//rowid is the internal function of Oracle.
>>Union:
*How to use Union(>>How to use Union>>Union and order by):
http://jims57.blog.163.com/blog/static/9513617200911281041548/edit/?mode=prev
>>SqlParameter:
*Output SqlParamter:(>>Output SqlParameter>>Out SqlParameter>>SQL Output SqlParameters>>Output Variables)
[C#]
SqlParameter.Direction=SqlParamterDirection.Output; //Set output parameter>>Set output variables>>Output SqlParameter>>Output parameter
[SQL] (>>output sql variables)
*How to use SqlParameter:(>>How to use sqlparameter>>use SqlParameter)
http://jims57.blog.163.com/blog/static/951361720091124114028907/edit/?mode=prev
*Get SQLParamter(>>Get SQLParameter by program>>Get SqlParameter value and Type>>GetSqlPatameters):
http://jims57.blog.163.com/blog/static/95136172009102651253186/edit/?mode=prev
*Loop to add SqlParameter(>>Loop to add SqlParameter>>Loop to add Parameter>>Loop to get SqlParameter):
http://jims57.blog.163.com/blog/static/951361720091120133044/edit/?mode=prev
http://jims57.blog.163.com/blog/static/9513617200911301459979/edit/?mode=prev
>>If else(>>If else):
*How to use SQL if else(>>How to use SQL if else>>SQL IF ELSE):
----Way 1----
IF (SELECT * FROM T1 WHERE DEA005 = '05')
BEGIN
SELECT * FROM T1 WHERE DEA005 = '05'
END
ELSE
BEGIN
SELECT * FROM T1 WHERE DEA005 <> '05' //Else can be: begin and end as well.
END
----Way 2----(>>Check sql variables>>Check null>>Check variable null)
[SQL]
if @Variable is null
begin
select * from table1
end
[C#]
----DataReader----
if (M_DR[(string)M_ArlFields[M_IntI]] is DBNull)//If it is the DBNull>>Check DR null>>Check DataReader null>>Check SqlDataReader Null
{
M_StrTempFieldValue = "";
}
----String----(>>Check C# empty>>Check C# null)
if(String.IsNullOrEmpty(txtUserName.Text)){//TODO;}
[SqlParameter]
if(SqlParameter.IsNullable)//>>Check SqlParameter null
{
////TODO;
}
>>Alias:
*Summary:
[SQL]
1.Can not use the alias to set value.e.g:
select T1.ID CaseID,Name from table1 T1 where table1.ID=T1.CaseID//It can not use alias like T1.CaseID to set value, it should use T1.ID to set.
>>Top 1(>>SQL Top 1>>Set value by top 1):
*Set the value by top 1:
Select top 1 @userID =ID from table1
*SQL Top info:(>>Top 100 percent)
Select * from (select top 100 percent from table1 where ID=1 order by Name) //In subquery, if you need to use "Order by", you must use "Top", like this.
>>Day of week:(>>Week days)
*Today week day:(>>Today week day)
---->>Get today week day----
System.DateTime.ToDay.DayOfWeek.ToString();//Return Money
>>DateDiff(SQL DateDiff):
*How to use DateDiff(>>How to use DateDiff):DATEDIFF ( datepart , startdate , enddate )
参数
datepart
是规定了应在日期的哪一部分计算差额的参数。下表列出了 Microsoft® SQL Server™ 识别的日期部分和缩写。日期部分 缩写
year yy, yyyy
quarter qq, q
Month mm, m
dayofyear dy, y
Day dd, d
Week wk, ww
Hour hh
minute mi, n
second ss, s
millisecond ms
----Example----
select CartID, Min(DateDiff(dd,DateAdded,GetDate())) from ShoppingCart group by CartID //>>DateDiff>>Min>>Group By>>GetDate()
>>Email:
*Send Email:(>>Send Email by C#>>SmtpClient)
using System.Web.Mail;//The namespace must be included in the class,or using System.Net.Mail;
SmtpClient SC=new StmpClient("SMTP IP address");//You can use the local SMTP server which should be installed in IIS, or external SMTP server like 163
MailMessage MM=new MailMessage("from","to","subject","body");
SC.Send(MailMessage);
>>Order By(>>OrderBy):
*Order by without duplicate rows(>>Order by without duplicate rows>>Order by AgentCount):
http://jims57.blog.163.com/blog/static/951361720091128114139864/edit/?mode=prev (Discussed with SSX and PHC on 2009-12-28)
*Customize order by search(>>Customize order by search>>Customized order by):
[SQL server]
select * from T
order by CHARINDEX('|' + LTRIM(RTRIM(STR(Id))) + '|', '|3|4|5|1|') desc //(>>SQL Trim)
**********************************
返回字符串中指定表达式的起始位置。
**********************************
>>Hashtable:
*How to use Hashtable(>>How to use Hashtable>>How to use Hashtable):
http://jims57.blog.163.com/blog/static/95136172009102481758998/edit/?mode=prev
*Hashtable namespace(>>Hashtable Namespace):
using System.Collections;
>>DictionaryEntry:
*How to use DictionaryEntry(>>How to use DictionaryEntry):
http://jims57.blog.163.com/blog/static/95136172009102645920927/edit/?mode=prev
>>If Exists(>>If Exists>>SQL Exists>>SQL Not Exists):
*How to use If Exists(>>How to use If Exists):
if exists(select * from table1)//Or if not exists(select * from table1)
begin
----Content----
end
else
begin
----Content for other action----
end
//When exists, do the content
>>Trigger:
*How to use the trigger in SQL server 2000(>>How to use Trigger in SQL server 2000>>Use SQL 2000 Trigger>>Use SQL server 2000 Trigger):
[SQL server 2000]
ALTER trigger [dispatcher].[Trig_AddWorkLogWhenAddCaseInfo] on [dispatcher].[tb_CaseInfo] for insert
AS
BEGIN
insert into tb_WorkLog(CaseID,UserID) select inserted.ID,inserted.UserID from inserted
END
//-----It can not use as insert into table1(ID) values (select inserted.ID from inserted). but SQL server 2008 can use with values in trigger.-----
//-----In SQL server, it has to use "Select inserted.ID from inserted" format to set the value of variable,like update tb_CaseInfo set tb_CaseInfo.ActionUserID=(select inserted.UserID from inserted) where tb_CaseInfo.ID=(select inserted.CaseID from Inserted)
*Trigger format(>>Trigger Format):
Insert, update: use inserted as the temporary table
delete: use deleted as the temporary table
>>ComboBox(>>Combo Box):
*Set ComboBox Text And Value:(>>Set Value And Text For ComboBox>>Set ComboBox Text And Value)
http://jims57.blog.163.com/blog/static/95136172009112311565281/edit/?mode=prev
*Select ComboBox item by text(>>select comboBox item by text>>Select ComboBox Value And Text By Text>>Select ComboBox by Text)
http://jims57.blog.163.com/blog/static/95136172009112950771/edit/?mode=prev
*ComboBox Event(>>ComboBox Event):
[Select Item](>>Select ComboBox Index Event>>Select ComboBox Event)
http://jims57.blog.163.com/blog/static/9513617200911230425417/edit/?mode=prev
*Set Child ComboBox(>>Set Child ComboBox>>set child comboBox>>Set comboBox child value and text):
http://jims57.blog.163.com/blog/static/9513617200911230157384/edit/?mode=prev
*ComboxBox Name Space(>>Combobox namespace>>Combobox name space>>Control Name space>>Control Namespace):
using System.Windows.Forms;
*Set ComboBox Value and Text by DataTable:(>>Set ComboBox Value and Text>>Set Combox Text and Value)
http://jims57.blog.163.com/blog/static/95136172009101295837703/edit/?mode=prev
*About SelectedText of ComboBox(>>SelectedText>>ComboBox SelectedText>>Combo Box SelectedText>>ComoBox Style>>ComboBox list type):
如果 DropDownStyle 设置为 DropDownList,则返回值是空字符串 ("")。
*Get the current text of ComboBox(>>Get dropdownlist current text>>Get comboBox selected text>>Combo Box Text>>ComboBox Text>>Get the current text of ComboBox>>Get ComboBox current Text>>Get ComboBox Text>>Combobox select text>>get ddl current text>>dropdownlist current text>>ComboBox Current Text>>DDL current text>>DDL Selected Text):
[WinForm]
this.CbxCompany.Text;//The text is the current selected text
[WebForm]
this.Ddl.SelectedItem.Text; //DropDownList control
*Get ComboBox Selected value(>>Get comboBox selected value>>Get combobox value)
[C#]
ComboBox.SelectedValue.ToString().Trim();//>>Dropdownlist selected value>>DDL current value>>ComboBox Current value
[ASP.Net]
DropdownList.SelectedItem.Value;
>>Byte:
*Get Byte from string:(>>Get byte from string>>Get Bytes from string)
[C#]
byte[] btContent = Encoding.GetEncoding("gb2312").GetBytes(strContent); //>>GetBytes>>GetEncoding>>Encoding
>>String:
*Delete String:(>>Delete string)
[ASP.Net]
1.StringBuilder sb=new StringBuilder("Heeeello"); sb.Re
*Connect string:(>>Connect string>>Join String)
[ASP.Net]
1.string M_Str=String.Concat("Hello"," ","World");//Return "Hello World"
2.String[] M_StrArray={"Hello","World"};
string M_Str=String.Join("**",M_StrArray);//Return "Hello**World". "**" is the delimiter
*Check startwith string:(>>Check Startwith string>>Startwith string>>Check endwith string>>Endwith string)
[ASP.Net]
bool b1="Hello".StartsWith("He");//Return "true"
bool b2="Hello".EndsWith("llo");//Return "true"
[SQL] (>>sql startwith)
select * from tb_Test where Name like '甘%' //It will search out all the user with surname "甘"
*Compare string:(>>Compare string)
[ASP.net]
1.bool b1=String.Compare(StrA,StrB);//StrA="Hello",StrB="World", so return -1.The return value can be {-1,0,1}
2.System.String StrA="Hello";
bool b1=StrA.CompareTo(StrB);//Return -1,if StrB="World".CompareTo is Case-Sensitive method.(>>CompareTo>>Compare To)
*Get String from Byte:(>>Get String from byte)
string strInfo = Encoding.GetEncoding("gb2312").GetString(bytes, 0, bytes.Length);
//bytes is a variable which record byte.>>GetString()>>GetEncoding>>Encoding>>Gb2312
*String Array:(>>String Array)
----Set String array----(>>Set String array>>String array>>New string array)
[1 D String array]
1.string[] M_Strs={"a","b"};//Do not use string[] M_Strs=new string{"a","b"};
2.String[] M_StrStr2=new String[2]{"A","B"};
----Foreach string array----
string[] names={"a","b","c"};
foreach(string s in names)
{
///TODO; }
[2 D String Array] (>>2D string Array>>2 D array>>2 D string array)
---->>Declare 2 D array----
int[,]=new int[2,2];
*String Builder:(>>How to use string builder>>How to use stringbuilder>>String Builder)
http://jims57.blog.163.com/blog/static/95136172010230111623796/
*String Format:(>>String Format>>How to use string format)
[ASP.Net]
1.<a id=RoomCategoryManLink href="<%=RoomCategoryManLink%>">房间类型管理 </a> //<%%> is to set the href with variable from server.
[C#]
1.<ASP:Label ID="ID" runat="server" Text='<%#String.Format("{0:0.00}",Eval("Price"))%>'> </ASP:Label> //>>Bind Data>>Eval>>String.Format
2.Label.Text=String.Format("{0:c}",amount);//c means the format will be currency one.>>Money Format>>Money String Format
3.<Asp:BoundField DataField="Money" DataFormatSring="{0:c}" HeaderText="Subtotal" ReadOnly="true" SortExpression="Subtotal"> //this is in GridView <Columns> >>ReadOnly>>BoundField>>HeaderText
*Segment String Class(>>Segment String Class):
http://blog.163.com/jims57/blog/static/951361720091024103518389
*How to use Split(>>Split>>How to use Split>>Split string):
[C#]
string[] M_StrCookies = M_StrCookie.Split(';');
[JS] (>>JS split>>Javascript split>>How to use js split>>how to use javascript split)
----Example----
My Example 1.
>>HttpWebRequest(>>HttpWebResponse):
*Summary about HttpWebRequest and HttpWebResponse(>>HttpWebRequest Summary>>HttpWebResponse Summary>>WebClient Summary>>WebBrowser Summary):
1. NameValueCollection myNameValueCollection = new NameValueCollection();
2. byte[] pagedata = wb.UploadValues("http://www.ip138.com:8080/search.asp", myNameValueCollection);
3. byte[] bResponse = wc.DownloadData(uri);
string strResponse = Encoding.ASCII.GetString(bResponse);
4. client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
5. WebClient webClient = new WebClient();
byte[] responseData = webClient.DownloadData(uriString);
string srcString = Encoding.UTF8.GetString(responseData);
6. webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); (>>Content-Type>>Content Type>>ContentType)
7. viewState = System.Web.HttpUtility.UrlEncode(viewState);
eventValidation = System.Web.HttpUtility.UrlEncode(eventValidation);
submitButton = System.Web.HttpUtility.UrlEncode(submitButton);
8. responseData = webClient.UploadData(uriString, "POST", postData);
9. DocumentCompleted Event;
10. tbPasswd.SetAttribute("value", "12345678");
11. btnSubmit.InvokeMember("click");
12. HtmlElement tbUserid = webBrowser.Document.13. String request = reader.ReadToEnd();
14. string postString = "userName=1&password=1" + "&loginButton=" + submitButton + "&__VIEWSTATE=" + viewState + "&__EVENTVALIDATION=" + eventValidation;
15. catch (WebException we)
{
string msg = we.Message;
}
16. 查看网页POST的数据还可以通过一些工具来查看,比如: 网页数据分析工具HttpWatch,网络嗅探器等。
17. 备注:以下为Post方式提交数据编码几种方式:
text/plain
以纯文本的形式传送
application/x-www-form-urlencoded
默认的编码形式,即URL编码形式
multipart/form-data
MIME编码,上传文件的表单必须选择该
18. HttpWebRequest
19. HtmlDocument htmlDoc = webBrowser.Document;
HtmlElement btnElement = htmlDoc.All["btnClose"];
if (btnElement != null)
{
btnElement.click += new HtmlElementEventHandler(HtmlBtnClose_Click);
}
20. formElement.AttachEventHandler("onsubmit", new EventHandler(HtmlForm_Submit));
21. Http Analyzer V2.
22. this.Text = this.webBrowser1.Document.ActiveElement.GetAttribute("href");
23. Private Sub WebBrowser_NewWindow(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles WebBrowser.NewWindow
Dim NewUrl As String
NewUrl = CType(sender, Windows.Forms.WebBrowser).Document.ActiveElement.GetAttribute("href")
Me.WebBrowser.Url = New Uri(NewUrl)
End Sub
24. string M_StrURL=((WebBrowser)sender).Document.ActiveElement.GetAttribute("href");
this.webBrowser2.Url = new Uri(M_StrURL);
25. (1) Create a web request
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://www.google.com");
(2) then create a web response for the request and then create a reader
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string strSite = reader.ReadToEnd();
25. Reflector查看了一下WebClient的代码,发现WebClient每次发请求(如DownloadString)时都会调用自己的一个叫GetWebRequest的方法。
26. 访问第一页时,服务器会返回一个Cookies值,打开第二页时要向服务器提交访问
第一页时返回的Cookies,才能打开页面。可以这样解决:
打开第一页时:
byte[] buff=webclient.DownloadData(url);
string cookie=webclient.ResponseHeaders.Get("Set-Cookie");
向第二页发送请求时:
webclient.Headers.Add("Cookie", cookie);
27. post方法访问站点,要注意的是:post一定要是大写,不然报403错误.
28. 对于aspx网页一定要注意viewstate,如果不post viewstate,后台程序是不会处理的.
29. 之所以能够保持 Session 和 Cookie 是因为使用了 Cookie 容器(CookieContainer),见红色的代码部分。
30. System.Text.Encoding.Default;(=UTF8) //>>Default Encoding
31.Console.WriteLine("/nHeader Name:{0}, Value :{1}",myHttpWebResponse.Headers.Keys[i],myHttpWebResponse.Headers[i]);
32.foreach (Cookie cookie in response.Cookies)
cookieContainer.Add(cookie);
33.cookieheader = req.CookieContainer.GetCookieHeader(new Uri(url));
34.HWRes.GetResponseHeader("Set-Cookie");
35.request.AllowAutoRedirect = true;
36.req.CookieContainer.GetCookieHeader(new Uri("http://www.5460.net/txl/login/login.pl"));
*How to Post Data By HttpWebRequest(>>How to post data by HttpWebRequest>>Send Data By HttpWebRequest>>how to use httpwebrequest>>how to use httpwebresponse):
[ASP.net] (>>HttpWebRequest and ASP.Net>>HttpWebResponse And ASP.net>>ASP.net and Cookie>>ASP.net and Session)
----Example 1----
http://jims57.blog.163.com/blog/static/951361720098161568643/edit/?mode=prev
----Link----
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx
>> ASP.Net(>>ASPX):
*WebBrower to get the cookie in ASP.net website(>>ASP.Net Cookie>>ASPX Cookie):
Webbrowser.document.cookie can not get ASP.NET_SessionId value
>>WebBrowser:
*WebBrowser url(>>WebBrowser URL>>WebBrowser URI):
[C#]
----2 ways----
this.webBrowser1.Url = new Uri("http://www.baidu.com");
this.webBrowser1.Navigate("http://203.143.139.35/codesk3/Authenticate.aspx");
*Control webPages(>>Control webPage>>WebBrowser control webpages>>Control websites>>Control webpages by webbrowser)
[C#]
private void button1_Click(object sender, EventArgs e)
{
this.webBrowser1.Url = new Uri("http://www.baidu.com");//Or this.webBrowser1.Navigate("http://203.143.139.35/codesk3/Authenticate.aspx");
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
MessageBox.Show(string.Format("Current URL is {0}",this.webBrowser1.Url.ToString()));
HtmlElement HEUserName = this.webBrowser1.Document.All["txtUserId"];
HtmlElement HEPWD = this.webBrowser1.Document.GetElementById("txtPassword");
HtmlElement HESubmit = this.webBrowser1.Document.GetElementById("imgLoginBtn");
HEUserName.SetAttribute("value", "chendej@cn.ibm.com");
HEPWD.SetAttribute("value", "chendej@cn.ibm.com");
HESubmit.InvokeMember("click");
}
>>DataTable:
*Create DataTable dynamically:(>>Create DataTable dynamically)
----Example----
Example 1. (>>add data to datatable>>Add data to datatable>>Define DataTable columns)
*DataTable rows:(>>DataTable Rows>>DataTable Row collection)
---->>Get DataTable row collection----
[ASP.Net]
DataRowCollection DRC=DataTable.Rows;
*DataTable Columns:(>>DataTable Columns>>DataTable Column collection)
---->>Get DataTable column collection----
[ASP.Net]
DataColumnCollection DCC=DataTable.Columns;
*DataTable load DataReader(>>DataTable load DataReader)
DataTable.Load(SqlDataReader);
*ImportRow(>>ImportRow>>Import Row>>DataTable.Clone()>>Clone datatable>>Copy DataTable):
DataTable=AnotherDataTable.Clone();//Before it can use the following importrow command, it has to use the command to clone the structure of datatable.
DataTable.ImportRow(AnotherDataTable.Rows[Index]);(>>Import datatable rows)
>>DataList:
*DataList Select Item Event:(>>DataList Select Item Event>>DataList Event>>DataList Button event)
http://jims57.blog.163.com/blog/static/9513617201022854838318/ //>>DataList Argument>>DataList Item Event
>>FindControl:(>>Find Controls)
*FormView Find Control:(>>FormView FindControl>>Find FormView Control)
Label MyLabel=FormView.FindControl("TitleTabel") as Label
>>DataView:
*Get DataView:(>>Get DataView)
[ASP.Net]
1.DataView DV=DataSet.Tables[0].DefaultView;//>>Get Default DataView
2.DataView DV=new DataView(DataSet.Tables[0],"BookAuthoer='Jim'","BookPrice",DataViewRowState.CurrentRows);
//BookPrice means sort by it,"CurrentRows" are not included the rows which are not changed,modified and new rows.
(>>DataView Row state>>DataView State>>New dataview>>New Data View)
*DataView Filter Row(>>Filter Row>>DataView Filter Row>>RowFilter>>Row Filter>>DV filter):
1.DataView.RowFilter = "ParentItemID=" + ItemID.ToString(); //>>Filter data by dataview
2.DV.RowFilter="BookAuthor='Jim'";
3.DV.RowFilter="(ID<20) and (username like '%user%')";
*Convert DataTable to DataView(>>Convert DataTable to DataView>>DataTable and DataView>>DataView and DataTable):
DataView thisView = new DataView(thisTable); //创建DataView对象(>>Get DataView)
----Convert DataView to DataTable----(>>Convert DataView to DataTable>>convert dataview to table)
M_DT=M_DV.ToTable();
>>TimeSpan(>>Time Span):
*How to use TimeSpan(>>How to use TimeSpan>>How to use Time Span):
[C#]
TimeSpan M_Tms = new TimeSpan(0, 3, 0, 0);
DateTime.Now-M_Dtm>T_Tms;//M_Dtm is another value of Datetime.
>>New Line(>>New Line>>New Row):
[C#]
*New line in TextBox:
this.TextBox1.Text="I will new a line/r/n";///r/n is the line new method.(>>/n>>/r)
>>Rownumber(>>Row_Number>>Row_Number()>>SQL row count>>SQL row number>>Get Row number in Procedure>>Get Procedure ID>>Get Procedure Row number):
[For SQL 2005]
select ROW_NUMBER() over (Order By tb_CaseInfo.Logged desc) as ID from Form1//Row_Number() can only be used in SQL after 2005 version.
>>GetType():
*Check the type of the Control(>>Check control type>>Control Type):
----Way 1----
if(Control.ControlCollection.GetType().Name=="TextBox")
{
Do something;
}
----Way 2----
if(Control.ControlCollection.GetType().ToString()=="System.Windows.Forms.TextBox")
{
Do something;
}
>>Control.ControlCollection(>>System.Windows.Forms):
*Reference Control.ControlCollection:
Before the control.ControlCollection can be used, it has to reference "System.Windows.Forms"
>>Procedure:
*Insert into format(>>Insert into format):
Insert into Form1(Name,Sex) values(@Name,@Sex)
*How to use Insert into select:(>>Insert Into select from)
INSERT INTO Form1([Name],[Loc]) select Name,Loc from Form2
GO
**************************************************************************************************************************************
[Be Noted]
a.Field count must be the same.
b.If Form1 has any trigger, we have to stop the trigger on the form before we can execute the above command in procedure in SQL server.
c.The field length in Form1 must be no less than the length you input form Form2.
***************************************************************************************************************************************
*Parameter in SQL server procedure(>>SqlParameter>>Parameter in Procedure>>Procedure Parameter>>SQL Procedure Parameter):
a.The Sequence of Parameter must not be the ordinal.
b.The count of Parameters has be the same.
*************************For Example***********************************
[Procedure]
ALTER PROCEDURE [dbo].[Proc_Test]
(
@Name Varchar(10)=null,//@Name is first one.
@Loc VarChar(10)=null
)
AS
BEGIN
insert into tb_Test(Name,Loc) values(@Name,@Loc)
END
[C#] (>>How to set SqlParameter In C#)
----Way 1----
SqlParameter[] M_P=new SqlParameter[2];
M_P[0] = new SqlParameter("@Loc", SqlDbType.VarChar, 20);//Loc is first one
M_P[1] = new SqlParameter("@Name", SqlDbType.VarChar, 20);//>>Set sqlparameter type
M_P[0].Value = "Loc333";
M_P[1].Value = "Name Jimd";
DB.DBManager.ExeNonByProc("Proc_Test", M_P);
----Way 2----
http://jims57.blog.163.com/blog/static/9513617201022592341885/
***********************************************************************
*Case-Sensitive in SQL(>>Procedure Upper>>Procedure Case-Sensitive>>Procedure Upper>>Procedure Case Sensitive):
[SQL Server]
Select distinct * from tb_AllCNAsset where upper(CNH)=@CNH //upper can make CNH to be the upper case.
*Like search in Procedure(>>Like Search in Procedure>>Procedure Like>>SQL like):
Select distinct * from tb_AllCNAsset where upper(CNH) like '%'+@CNH+'%'
>>Window:
*Window Handling>>(>>Window Handling>>Handle Window)
[JS](>>JS handle window)
---->>New JS window----
var oWin=window.open("http://www.163.com","_blank","height=300,width=400,top=30,left=40,resizable=yes");//_blank={_self,_parent,_top,_blank}(>>open window>>new window>>open JS window>>new js window)
----->>Close JS window----
oWin.close();//>>Close JS window>>JS close window
---->>Open JS window----(>>Open JS previous windows)
oWin.opener;//Use .opener properties to open the previous window
---->>Other JS window----
oWin.history.go(-1);//Go back to the previous,oWin.history.back();
oWin.history.go(1);//Forward next window,oWin.history.forwared();
*User Windows:(>>User windows)
---->>Prompt window----
[JS](>>Js prompt windows)
var sInput=prompt("Input the name","Jim");//Jim is the default value.
---->>Tip Windows----
[JS](>>JS tip windows>>JS alert windows)
alert("I am the alert.");
---->>Confirm window----
[JS](>>JS confirm windows>>JS confirmation windows)
if(confirm("delete or not?"))
{
alert("Deleted.")
}
else
{
alert("No not del.");
}
>>Text:
*Different between text and Ntext in SQL server(>>NText>>Different between Text and Ntext):
[Text]->For pure English and Number
[NText]->For including Chinese Characters.[Unicode]
>>DateTime(>>Date And Time>> Date Time):
*Get DateTime:(>>Get DateTime)
[JS](>>Get JS dateTime>>Get Javascript Datetime)
var MyDate=new Date();//>>New JS datetime
var iMonth=MyDate.getMonth+1;//the month number begin from 0, so you must plus 1.(>>Get JS current month)
*Get the current DateTime:(>>Get current date time>>Get current datetime>>GetDate()>>Get current DT)
[SQL server]
GetDate();//In SQL server, use this way to get the current datetime;//>>Get SQL current Datetime>>Get SQL current Date And Time
[C#]
DateTime.Now;
*DateTime type:(>>DateTime type>>Date Time Type>>Variable Type>>Variables Type)
SmallDateTime:Accurate to minutes, 4 memory.//>>SmallDateTime.
DateTime:More accurate, 8 memory.
*Format Datetime(>>DateTime format>>Format DateTime):
[C#] (>>C# datetime format)
string StrMyDateTime=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//Month must be "MM",if want to represent as 24 hours format, must be used "HH",otherwise use "hh".
[Oracle] (>>Set Oracle datetime format>>Oracle datetime format>>Oracle date format)
##----SQL----##
select to_char(sysdate,'mm/dd/yy') from dual //(>>Oracle to_char>>Change oracle date format)
>>DataReader(>>SqlDataReader>>DR):
*DR Summary:(>>DR Summary>>DataReader Summary>>SqlDataReader Summary)
1.When return DR in an object, and the DR has been used the method to get the first row, DR.Read(), so in another class, you do not need to DR.Read().
That is to say, the DR.Read() in a class will effect the another class access the DR.
*SqlDataReader HasRow:(>>SqlDataReader HasRows>>HasRows>>SqlDataReader.HasRows)
if(SqlDataReader.HasRows)
{
Do Something;
}
*Get name of column of DataReader(>>Get DataReader Column name>>SqlDataReader Column name>>Get SqlDataReader Field Names>>SQLDataReader Field name>>DataReader Field Name>>Get DR field name):
[C#]
SqlDataReader.GetName(0);Get the name of column 1
*Check if the value is DBnull(>>SqlDataReader DBNull>>SqlDataReader Null>>DBNull>>DataReader Null>>SqlDataReader Null>>DR null>>Null):
if(SqlDataReader[0] is DBnull)
{
MessageBox.Show("It is the DBNull.");
}
else
{
MessageBox.Show("It is not the DBNull.");
}
*Get Count of DataReader Filed(>>DataReader Field count>>Get Column number>>Get DataReader Field count>>SqlDataReader Field Count>>Get SqlDataReader Field Count):
SqlDataReader.FieldCount;//Get count of SqlDataReader.
*Get value method of SqlDataReader(>>Get DR value>>Get DataReader value>>Get SqlDataReader Value>>DataReader Get Value>>SqlDataReader Get Value):
SqlDataReader.GetBoolean(0);//if the 0 column is bit in SQL database, it can get the "true" or "false" by the way directly.
SqlDataReader.GetInt32(0);//Get the value of column in Database,which is "int" type.
SqlDataReader.GetString(Index);
SqlDataReader.GetValue(M_IntI).ToString();//The basic method
SqlDataReader["FieldName"].ToString();//>>Get DR Value by Field name
SqlDataReader.GetValue(SqlDataReader.GetOrdinal("FieldName"));//>>Get DR Field index by Field name
(
>>?:):
*How to use IIF:
[C#]
int I=IsAdmin=="Admin"?1:0;//If the "IsAdmin" equals "admin",return 1,if not, return 0
>>TextBox:
*Set focus for the TextBox(
>>Set Focus for TextBox
>>TextBox Focus
>>TextBox.Focus()
>>TextBox.Select()
>>TextBox Get focus):
[C#]
this.TextBox1.Select();//Have to use "Select()" before the "Focus()" takes effect.
this.TextBox1.Focus();//Get the focus
>>ArrayList(>>Array List):
*Find ArrayList Items:(>>Find ArrayList Items>>Search for ArrayList items)
[ASP.Net]
int M_IntFoundItemIndex=ArrayList.BinarySearch(7);//Find 7 index in ArrayList, index begin as 0.
*Sort ArrayList Item:(>>Sort ArrayList Items>>Sort arraylist data)
[ASP.Net]
1.ArrayList.Sort();//If {5,4,3,2,1} become {1,2,3,4,5}
2.public virtual void Sort(IComparer M_Comparer); See example.
*Remove ArrayList Item(>>Remove arraylist items>>Delete ArrayList Items>>Delete Items)
[ASP.Net]
1.ArrayList.Remove("ItemName");
2.ArrayList.RemoveAt(ItemIndexYouWantToRemove);
3.ArrayList.Remove(BeginIndexOfRemoving,RemoveCount);
*Add Item to ArrayList:(>>Add item to ArrayList>>Add items to ArrayList>>Add ArrayList Items)
----Add Item----
[ASP.Net]
1.ArrayList.Add("Value");
2.ArrayList.AddRange(AnotherArrayList);//Add "Hello 1" and "Hello 2" to it, if AnotherArrayList have the two values.
----Insert Items----(Mean the added item will be added any where you want)
[ASP.Net] (>>Insert item to ArrayList)
1.ArrayList.Insert(Index,ArrayList2);//Index begin as 0.If Index=1, it mans the added item will be inserted into the 2 place. See example.
*New ArrayList:(>>New arraylist)
[ASP.Net]
ArrayList M_Ary=new ArrayList();//Do not specify the count of arraylist, Default=16.If items is over the capacity of arraylist, it will add capacity by 1 times.
ArrayList M_Ary=new ArrayList(50);//Specify the capacity of the arraylist.
[JS]
var iNumbers=new Array();
*ArrayList Count(>>ArrayList Count>>ArrayList.Count>>Get ArrayList Count):
ArrayList.Count to get the actual count ArrayList has
*Clear records in Arraylist(>>Clear ArrayList>>ArrayList.Clear())
ArrayList.Clear();//Clear all the records in the ArrayList
*Reference ArrayList(>>ArrayList reference>>Reference ArrayList>>ArrayList Namespace):
using System.Collections;//Before we are capable of using the "ArrayList",we have to reference it.
>>MessageBox(>>Message Box>>Info template>>Message template):
*MessageBox Tip Template(>>Messagebox template):
----Template 1----(About Warning>>Messagebox Warning template)
MessageBox.Show("Error:An unexpected error happens,maybe the coDesk is not reachable, please try again.","Tip",MessageBoxButtons.OK,MessageBoxIcon.Warning);
----Template 2----(>>MessageBox Tip Template>>MessageBox information Template>><essagebox info template)
MessageBox.Show("Error:An unexpected error happens,maybe the coDesk is not reachable, please try again.","Tip",MessageBoxButtons.OK,MessageBoxIcon.Question);
----Template 3----(>>Messagebox error template)
MessageBox.Show("Error:An unexpected error happens,maybe the coDesk is not reachable, please try again.","Tip",MessageBoxButtons.OK,MessageBoxIcon.Error);
*Confirmation of MessageBox(>>DialogResult.Yes>>MessageBox Confirmation>>Confirm message>>Confirm MessageBox):
[WinForm]
if (DialogResult.Yes == MessageBox.Show("You do not input any note for the current action, do you want it empty?", "Tip", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
{
this.Hide();
}
[WebForm](>>WebForm Confrim Message>>Web form confirm message>>JS confirm message>>Javascript Confirm Message)
----Example----(>>Webform Confirm Message)
Example 1.(>>Attribute)
*MessageBox NameSpace(>>MessageBox NameSpace>>MessageBox Name Space):
using System.Windows.Forms;
*Newline in Messagebox(
>>Change Line
>>Change MessageBox Line>>MessageBox new line):
MessageBox.Show("Do you want to change a new line?/nI am a new line.");//The /n is the new line in MessageBox
>>Number:
*Check number:(>>Check number>>Check if number)
[JS] (>>JS check number)
if(isNaN(iNumber))//Use isNaN to check if the number, iNumber is a variable.
{
}
[]
*Number format(>>Number Format>>Number Validation):
[.Net] (>>.Net check number)
Regex.IsMatch(P_str_num, "^[0-9]*$");
**********************************************************************************************
Before using "Regex",we have to reference the namespace "using System.Text.RegularExpression;" (>>Regex Namespace)
**********************************************************************************************
>>Path:
*Get absolute path:(>>Absolute Path>>Get path)
[ASP.Net]
Server.MapPath("./AFolder/")+fileName;//>>Relative path
Request.Url.AbsolutePath;(>>Get Absolute path)
Request.Url.ToString();//Get the full path of current page
Request.ApplicationPath;(>>Get Application Path>>Application Path)//Get the application path,you can use it by:
Response.Redirect(Request.ApplicationPath+"/Page.Aspx"); //>>Redirect>>Response.Redirect
@"http://"+HttpContext.Current.Request.Url.Host+HttpContext.Current.Request.ApplicationPath;//>>Get full application path>>Get full website path
*Get the startup path(>>Get Startup Path>>Startup path>>Start Up Path):
[C#]
System.Environment.CurrentDirectory;//Get the current directory of software startup.
*Path represent:(>>current path)
[C#]
“../”==The directory above the current directory
"./"==Current directory
>>IO:
*Reference for StreamReader and StreamWriter(>>StreamReader Reference>>StreamWriter Reference>>System.IO):
Before we can use the StreamReader and StreamWriter, we have to reference "using System.IO"
>>XML:
*Creat XML file(>>Creat XML File):
[C#]
----Way 1----
using System.Xml//reference System.Xml name space
new XmlDoucment XD=new XmlDocument();//Set up a new XML document
XD.LoadXml("<Root><Name>Jim</Name></Root>");//Use LoadXml method to fill the object XD
XD.Save("C://jim.xml");//Save the XML content into XML file
*Read XML File(>>Read XML File>>Display XML content):
[C#]
----Way 1----
using System.Xml
XmlDocument XD=new XmlDocument();
XD.Load("C://jim.xml");//Load into the specific XML file into the object of XML
XmlNodeReader reader=null;//Use the XmlNodeReader object to read XML data
reader=new XmlNodeReader(XD);//Copy the content in XD into reader
string s="";
while(read.Read())
{
switch(reader.NodeType)//Judge the type of XML node
{
Case XmlNodeType.Element:
s=reader.Name;
break;
Case XMLNodeType.Text:
if(s.Equals("Name"))
string strNeedValue=reader.Value;
else
}
}
----Way 2----
using System.Xml;
XmlDataDocument DD = new XmlDataDocument();//XmlDataDocument is only the data format for XML
StreamReader SR = new StreamReader(@"C:/jim.xml");//Use jim.xml make the streamReader object
DD.DataSet.ReadXml(SR);
this.Text = DD.DataSet.Tables[0].Rows[1][0].ToString();
----Way 3----
string GotContentFromXML=XMLFile.GetElementsByTagName("ATagName").Item(0).InnerXml; //Get XML element by tag name
*Change XML file content(>>Change XML file>>Modify XML file):
[C#]
----Way 1----
XmlDocument XD2 = new XmlDocument();
XD2.Load(@"C:/jim.xml");
XmlNode n = XD2.SelectSingleNode("//SN");//Has to user "//"
n.FirstChild.Value = "Jims88";//FirstChild means the SN node,that is the current node
XD2.Save(@"C:/jim.xml");
*****************************
----jim.xml content------
<E>
<No1>
<Name>Jims88</Name>
<SN>Jims88</SN>
</No1>
</E>
*****************************
----Way 2----
XmlDocument doc=new XmlDocument();
doc.Load(@"C:/jim.xml");
foreach (XmlNode node in doc.SelectNodes("//price"))//doc.SelectNodes is a collection of "price" nodes
{
node.InnerText = (XmlConvert.ToDouble(node.InnerText) * 1.2).ToString();//Set the value for each node named "price" after the related calculation
}
doc.Save(@"C:/jim.xml");//Have to save the XML file to upate the changed data
----Way 3----
XmlDocument XD = new XmlDocument();
XD.Load(@"C:/jim.xml");
XmlNodeList NL = XD.GetElementsByTagName("Name");//XmlNodeList is the collection of XML nodes.
foreach (XmlNode n in NL)
{
n.InnerText = "kkkk";
}
XD.Save(@"C:/jim.xml");
----Way 4----(>>Change XML using DataSet)
XmlDataDocument XDD = new XmlDataDocument();
StreamReader SR=new StreamReader(@"C:/jim.xml");
XDD.DataSet.ReadXml(SR);
DataSet DS=XDD.DataSet;
DataTable DT = DS.Tables[0];
DT.Rows[0][0] = "ChangedValue";//Change value
DS.AcceptChanges();//The method is not the necessary to do in changing the value of a XML file.
SR.Close();//Have to close the StreamReader before using StreamWriter
StreamWriter SW = new StreamWriter(@"C:/jim.xml");
XDD.DataSet.WriteXml(SW);
*XML node case sensitive(>>XML Case Sensitive):
XmlNodeList NL=XD.SelectNodes("//Name");//The "N" in Name must be upper case
*XML Node Array(>>XML Array>>XML Node Array):
XmlNodeList NL=XmlDoc.SelectNodes("//Name");
>>Control Website(>>Third party Provider>>Control Website>>Component Websites):
*Control Website Link:
http://www.devexpress.com
[>>Ajax>>Silverlight]
http://www.componentart.com/default.aspx
>>RegularExpression(>>Regular Expression>>Regex):
*Regex NameSpace(>>Regex NameSpace>>Regex Name Space):
using System.Text.RegularExpressions;
*Meta-Character for the RegularExpression(
>>Meta-Character
>>Regex Symbol):
http://www.exforsys.com/tutorials/csharp/regular-expressions-and-csharp-.net.html
*URL format(
>>URL Form
>>Web address Format
>>Web Address
>>URL Validation
>>Validate URL):
http://([/w-]+/.)+[/w-]+(/[/w- ./?%&=]*)?
*All English letter format(
>>English Letter format):
Regex.IsMatch(P_Str,"^[a-zA-Z]*$");
*IP format(
>>IP Format
>>Validate IP address
>>IP address validation):
----Way 1----
string t11 = "55.54.53.52";
string p11 = "^" +
@"([01]?/d/d|2[0-4]/d|25[0-5])/." +
@"([01]?/d/d|2[0-4]/d|25[0-5])/." +
@"([01]?/d/d|2[0-4]/d|25[0-5])/." +
@"([01]?/d/d|2[0-4]/d|25[0-5])" +
"$";
Match m11 = Regex.Match(t11, p11);
----Way 2----
string StrPattern=@"^(0|[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-5])/.(0|[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-5])/.(0|[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-5])/.(0|[1-9][0-9]?|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
Regex.IsMatch(this.TextBox1.Text,StrPattern);
>>Report(
>>ReportDocument):
*How to use the report Doucment(
>>Report Document):
ReportDocument r=new ReportDocument();
string strReportPath;
r.Load(strReportPath);
r.DataDefinition.RecordSelectionFormula=strSQL;
>>Application:
*Application data:(>>Application data>>Application share data)
---->>Set application data----
[ASP.Net]
Application.Add("key1","value1");
---->>Get application data----
[ASP.Net]
Application.Contents["key1"];
>>Application.StartupPath(>>Startup>>//):
[C#]
Application.StartupPath.ToString()+"//Jim.txt"
//System will just show "/"
>>IndexOf:
*How to use IndexOf :
[C#]
int i;
i="12345".IndexOf("3");
//i will be 2.
//Index begin from 0
//When found no, return -1
----Exmaple 1----
http://jims57.blog.163.com/blog/static/9513617200992972216301/edit/?mode=prev
>>OpenFileDialog:
*How to use the OpenFileDialog:
OpenFileDialog OFD = new OpenFileDialog();
OFD.Filter = "Word Files (*.docx)|*.docx|All Files(*.*)|*.*";
if(OFD.ShowDialog()==DialogResult.OK)
{
MessageBox.Show("Press OK button.");
this.label1.Text = "Your selected file name is " + OFD.FileName.ToString();
}
>>Label:
*Get the label text(>>Label Text):
>>Search:
*.Net Lucene data(>>Lucene>>.Net):
Link:http://incubator.apache.org/lucene.net/docs/2.1/
>>DoEvents:
*DoEvents(>>VBA DoEvents):
This action can go on doing the action while opening the IE:
Set IE = Nothing
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.navigate "http://203.143.139.35/codesk3/Incident/AgentHome.aspx"
Do Until IE.readyState = 4
DoEvents
Loop
>>Microsoft Internet Control:
*Reference "Microsoft Internet Control"(>>Shdocvw.dll>>Reference>>Controls)
Add "Shdocvw.dll" in Reference of Excel VBA
>>Property:
*Set Property:(>>Set Property)
[C#] (>>c# property)
----Example----
Example 1.
----Info----
Info 1.(>>Attribute>>what is attribute>>What is property)
*Difference between property and attribute:(>>Difference between property and attribute>>Property and Attribute)
Info 2.
Info 3.
>>Form:
*The difference among Close,Hide and Dispose(>>Form.Close()>>Form.Hide()>>Form.Dispose()):
[Form.Close()]
Close the form, but it doesn't release the related resource.
[Form.Hide()]
Hide the form, after that, the form can not show by "Form.Show()", the related resource is not released.
[Form.Dispose()]
The resource of the form will be released.
*The difference between ShowDialog and Show(>>ShowDialog>>Show>>Different between ShowDialog and show>>Different between Show and ShowDialog):
[ShowDialog]
After "ShowDialog", for instance, Form.ShowDialog();, the following sentence will not be executed.
[Show]
After "Show",the following sentence will go on executing.
************************************************************************
Link: http://hi.baidu.com/hooyan/blog/item/66d567a708145c92d0435844.html
************************************************************************
*Close form(>>Form close handler>>Close Form EventArgs>>Form Closing>>Form.Closing>>Form close event>>Form Event):
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FrmServerSetting_FormClosing);//Have to add the handler when form is loading
private void FrmServerSetting_FormClosing(object sender, FormClosingEventArgs e)//Form closing event
{
if (MessageBox.Show("Are you sure to exit the application?", "CoDesk Assistant Tip", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)//Want to quit the application
{
}
else
{
}
}
*Show User form(>>Show Form>>Show User Form>>Hide form):
[C#]
----Way 1----
this.Show();//Show the current form
this.Hide();//Hide the current form
----Way 2----
Form1 frm=new Form1();
frm.Show();
----Way 3----
Form1 frm=new Form1();
Frm.ShowDialog();
>>Length:
*The Length of array(>>Array Length>>array size):
---->>Get Array size----(>>Get array length)
[C#|ASP.net](>>GetLength(0)>>Get length)
int[] Ary=new int{1,2,3}
int a=Ary.Length //a=3
or
int b=Ary.GetLength(0);//b=3, Getlength(0) means get the array length.
[JS]
array.length;//L must be lower case.
[jQuery]
$("div").size(); //$("div").get(); ,use it to get the array object. (>>Get array object)
>>Count:
*The Count method in IE(>>Length):
Xbody.Childnoes.length
>>IE(>>Internet Explorer>>Explorer):
*Get the opened IE object(>>IE Object):
HH:
Dim SWs As ShellWindows
Set SWs = New ShellWindows
Dim IEW As InternetExplorer
For Each IEW In SWs
Do Until IEW.readyState = 4
DoEvents
Loop
If TypeOf IEW.document Is HTMLDocument And Trim(IEW.document.Title) = "coDesk - Search User" Then
IEW.document.frmUserSearch.txtSearchUser.Value = "12345"
GoTo GotOne:
End If
Next
GoTo HH:
GotOne:
MsgBox "Find one!"
Set IEW = Nothing
Set WSs = Nothing
*How to use IE in VBA(>>Connect IE>>Create IE>>Use IE>>Reference IE>>Create IE Object):
Set IE=CreateObject("InternetExplorer.Application")
IE.Visible=true
IE.Navigate "www.baidu.com"
Set IE=Nothing
*Test the Loading status of IE(>>IE status):
Do until IE.ReadyState=4 '4 means the IE has loaded totally
Do Sth.
Loop
>>IE Document Object(>>Document):
*Document event:(>>Document events)
---->>Document Onclick event----
>>Sleep(>>Wait):
*How to use the Sleep sub
Private Declare Sub Sleep Lib "Kernel32"(ByVal dwMilliseconds as Long)
Sub MySub()
Sleep(5000)'Or Sleep 5000
End Sub
***********************************
Type the sentence before the sub
The "S" in Sleep must be Uppercase.
***********************************
>>Dir(>>FileSearch):
*The replacement for the Application.FileSearch:
Sub Open_All_Files()
Dim oWbk As Workbook
Dim sFil As String
Dim sPath As String
sPath = "C:/Documents and Settings/Roy Cox/My Documents/" 'location of files
ChDir sPath
sFil = Dir("*.xlsx") 'change or add formats
Do While sFil <> "" 'will start LOOP until all files in folder sPath have been looped through Set oWbk = Workbooks.Open(sPath & "/" & sFil) 'opens the file
' do something
oWbk.Close True 'close the workbook, saving changes
sFil = Dir
Loop ' End of LOOP
End Sub
>>Excel file:
*Read the data without opening the Excel file(>>Read Excel Data>>Connect to Excel database):
Dim ObjApp As Excel.Application
Dim ObjWorkbook As Excel.Workbook
Dim ObjWorksheet As Excel.Worksheet
Dim IntWSNo As Integer
Set ObjApp = CreateObject("Excel.Application")
Set ObjWorkbook = ObjApp.Workbooks.Open(ThisWorkbook.Path & "/Test2.xlsx")
ObjApp.Visible = False
Set ObjWorksheet = ObjWorkbook.Worksheets(1)
IntWSNo = ObjWorkbook.Worksheets.Count
ObjWorkbook.Close
ObjApp.Quit
Set ObjWorksheet = Nothing
Set ObjWorkbook = Nothing
Set ObjApp = Nothing
>>Case(>>Case>>UpperCase>>LowerCase>>Lower Case>>C# UpperCase>>C# Upper Case>>C# Lower Case>>C# LowerCase>> To upper case):
*Change case:(>>Change case)
[C#]
string.ToUpper();
string.ToLower();
[Javascript]
"stringvalue".toUpperCase();//Become "STRINGVALUE",
"STR".toLowerCase();
>>Case:
*The Upercase in SQL(
>>UCase
>>Uppercase):
StrSQL = "Select * from [CN$] where UCase(Login_ID) like '%CNH" & FindValue & "%'"
>>Field:
*Combine Fields:(>>Combine fields)
[Oracle] (>>Combine oracle fields)
##----SQL----##
SELECT员工职位 ||’ ’ ||员工姓名||’出身于’||出身日期 as 员工出身信息 FROM 员工基本信息表; //Use || to combine the more than 1 field in Oracle
*Field Values:(>>Field Values)
---->>Get Field Values----
---->>ASPxGridView----(>>Get ASPxGridView Field Values)
----Example1----(>>Get ASPxGridView Selected Field Values)
*SQL search Text field in Excel(>>Text Field):
StrSQL = "Select * from [CN$] where Login_ID='cnh" & Cells(Target.Row, Target.Column).Value & "'"
>>Connection:
*Check the State of Connection(>>Connection.State>>ConnectionState>>Connection state):
----How to use----
[C#]
if (Con.State != ConnectionState.Closed)
{
Con.Open();
}
---->>Connection State type----(>>Connection state type)
http://jims57.blog.163.com/blog/static/95136172010368561032/
*Execure SQL(
>>SQL)
Con.execute SQL=RS.Open Sql,Con
*Excel connect to Access(
>>Connect to Access
>>Excel connect to Access
>>Connect Access
>>Access):
[Connection to Access 2003]
Set Con=new ADODB.Connection
With Con
.ConnectionString="Provider=microsoft.jet.oledb.4.0;Data Source=C:/Access.mdb"
.Open
End With
Set RS=New ADODB.RecordSet
RS.Open Sql,Con,adOpenKeySet,adLockOptimistic'Can not use Set RS=Con.Execute(SQL),which will show -1
[Connect to Access 2007] [Method 1]
StrAccessPath = ThisWorkbook.Path & "/PhilipsDB.accdb"
'Set the connection
Set Con = New ADODB.Connection
With Con
.ConnectionString = "Provider=Microsoft.ACE.oledb.12.0;Data Source=" & StrAccessPath
.Open
End With
Set RS=New ADODB.RecordSet
RS.Open Sql,Con,adOpenKeySet,adLockOptimistic'Can not use Set RS=Con.Execute(SQL),which will show -1
[Connect to Access 2007] [Method 2]
StrAccessPath = ThisWorkbook.Path & "/PhilipsDB.accdb"
'Set the connection
Set Con = New ADODB.Connection
With Con
.Provider = "Microsoft.ACE.oledb.12.0"
.Open StrAccessPath
End With
>>DataSet