HashFlare
IT圈子 - IT CONSULTANT

official website: press.one

blog: https://blog.press.one

explain:

你该如何证明你是你? https://mp.weixin.qq.com/s/f9I7d2mGKyWLstp-WOYPEA

https://press.one/p/address/v?s=02112035d679bc6ab479f1bed0fe83783c1ca1ab3f4a742fa1b1fa00c9b0e0ccfc747334bac858399573c7f8705b6b3df6f42dc96960618ed5032a347f393cbe0&h=c8a2c4fdc2df9b762b0c7bc4377066744db5aadc10c66b741bf8a1c9c9125cd0&a=20984de7c9c35174eb8cef497174ecb0b36fe687&f=P1&v=2

 

1.Test Task Async DeadLocks

Demo Code  (I am using winform app to demonstrate deadlocks which also happens on asp.net, but Console app don’t have such problem, even without calling Task.ConfigureAwait(false),codes that being ‘await’ will executed in new thread)

different between Task and Thread:

a.Task has return value (**Task.Result / **Task.GetAwaiter().GetResult())

b.Task run on created (Run/StartNew), Thread need Start after New

c.Task accept delegate/lamda, Thread accept object

d.Task can catch exception(after call ***Task.Wait() / ***Task.Result), Thread can not

Task.Run vs Task.Factory.StartNew

Task.Run Etiquette Examples: Don’t Use Task.Run in the Implementation

 

2.async await

Async Return Types

.Result and await block main Thread, ContinueWith doesn’t

 

await Task vs (Task<T> AsyncMethod).Result

async Task VS async Void  VS async Task<T>

A Tour of Task, Part 6: Results In short, await should be your go-to option for retrieving task results. The vast majority of the time, await should be used instead of Wait, Result, Exception, or GetAwaiter().GetResult().

 

Await on a completed task same as task.Result?

warning: warning CS1998: This async method lacks ‘await’ operators and will run synchronously. Consider using the ‘await’ operator to await non-blocking API calls, or ‘await Task.Run(…)’ to do CPU-bound work on a background thread.

http://stackoverflow.com/questions/13243975/suppress-warning-cs1998-this-async-method-lacks-await

Error: An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async=”true” %>.

http://stackoverflow.com/questions/13647346/calling-async-method-in-controller

Error: DeadLocks

[box title=”Don’t Block on Async Code”]

from http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

// My “library” method.
public static async Task<JObject> GetJsonAsync(Uri uri)
{
using (var client = new HttpClient())
{
var jsonString = await client.GetStringAsync(uri);
return JObject.Parse(jsonString);
}
}
// My “top-level” method.
public void Button1_Click(…)
{
var jsonTask = GetJsonAsync(…);
textBox1.Text = jsonTask.Result;
}

The top-level method calls GetJsonAsync (within the UI/ASP.NET context).
GetJsonAsync starts the REST request by calling HttpClient.GetStringAsync (still within the context).
GetStringAsync returns an uncompleted Task, indicating the REST request is not complete.
GetJsonAsync awaits the Task returned by GetStringAsync. The context is captured and will be used to continue running the GetJsonAsync method later. GetJsonAsync returns an uncompleted Task, indicating that the GetJsonAsync method is not complete.
The top-level method synchronously blocks on the Task returned by GetJsonAsync. This blocks the context thread.
… Eventually, the REST request will complete. This completes the Task that was returned by GetStringAsync.
The continuation for GetJsonAsync is now ready to run, and it waits for the context to be available so it can execute in the context.
Deadlock. The top-level method is blocking the context thread, waiting for GetJsonAsync to complete, and GetJsonAsync is waiting for the context to be free so it can complete.

Preventing the Deadlock

There are two best practices (both covered in my intro post) that avoid this situation:

In your “library” async methods, use ConfigureAwait(false) wherever possible.
Don’t block on Tasks; use async all the way down.

Consider the first best practice. The new “library” method looks like this:

public static async Task<JObject> GetJsonAsync(Uri uri)
{
using (var client = new HttpClient())
{
var jsonString = await client.GetStringAsync(uri).ConfigureAwait(false);
return JObject.Parse(jsonString);
}
}

This changes the continuation behavior of GetJsonAsync so that it does not resume on the context. Instead, GetJsonAsync will resume on a thread pool thread. This enables GetJsonAsync to complete the Task it returned without having to re-enter the context.

Consider the second best practice. The new “top-level” methods look like this:

public async void Button1_Click(…)
{
var json = await GetJsonAsync(…);
textBox1.Text = json;
}

public class MyController : ApiController
{
public async Task<string> Get()
{
var json = await GetJsonAsync(…);
return json.ToString();
}
}

This changes the blocking behavior of the top-level methods so that the context is never actually blocked; all “waits” are “asynchronous waits”.

Note: It is best to apply both best practices. Either one will prevent the deadlock, but both must be applied to achieve maximum performance and responsiveness.

[/box]

Calling async method synchronously

void Func(){

Task<string> sCode = Task.Run(async () =>
{
string msg =await GenerateCodeAsync();
return msg;
});

}

3.Threading.Timer run Async Task

Sometimes you may encounter such a requirement that you have a timer, and you have to do a async operation inside timer’s callback which is a sync method.

(in Java they have TimerTask, but seems in C# we don’t have the equivalent class)

a.try Nito.AsyncEx – https://github.com/StephenCleary/AsyncEx

How to call asynchronous method from synchronous method in C#?

Explicitly use a Func for asynchronous lambda function when Action overload is available

b.Task based timer implement:

Is there a Task based replacement for System.Threading.Timer?

How to implement Task Async for a timer in C#?

c.I found this alternative ‘solution’, but this approach is proved not reliable.

var t = new System.Threading.Timer(async (object state) =>
{
await aysncOperation();
Console.WriteLine(“Tmr Callback on: ” + Thread.CurrentThread.ManagedThreadId);
});

here is why this approach can not work as we expect: Potential pitfalls to avoid when passing around async lambdas

 

references:

All about .NET Timers – A Comparison

MSDN:Asynchronous Programming with Async and Await (C# and Visual Basic)

Best Practices in Asynchronous Programming

Task-based Asynchronous Pattern

async & await 的前世今生

走进异步世界-犯傻也值得分享:ConfigureAwait(false)使用经验分享

C#中async编程完全代替了Task了吗

#############

System.Timers.Timer “single-threaded” usage

System.Timers.Timer t;
 
void StartTimer()  {
  t = new System.Timers.Timer();
  t.Interval = 500;
  t.AutoReset = false;
  t.Elapsed += TimerProc;
  t.Enabled = true;
}
 
void TimerProc(object sender, System.Timers.ElapsedEventArgs e) {
  Task();
  t.Enabled = true;
}
 
void Task() {
}
https://www.codeproject.com/Questions/405564/Syste-Timers-Timer-single-threaded-usage

###############

4. k__backingfield

Use DataContract DataMember, add reference System.Runtime.Serialization

 

5.there is already datareader associated with this command

http://devproconnections.com/development/solving-net-scalability-problem

6. Iterate Datetime beware of your datetime string, especially when the source is from excel

string dateStr=”2016-01-01 11:59:59″;

DateTime.ParseExtrat(dateStr,”yyyy-MM-dd”,null)  ,  result is 2016-01-01 00:00:00 (12:00:00 am)

string dateStr=”27/1/2011  11:27:19 AM”;

DateTime.TryParseExact(***, “d/M/yyyy h:m:s tt”, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)

string myValue = “12:00:00.000”;

DateTime myDate = DateTime.ParseExact(myValue, “HH:mm:ss:fff”);

C# DateTime Format: A Concise Explanation for Beginners

https://blog.udemy.com/c-sharp-datetime-format/

7.network folder

Unhandled Exception: System.ArgumentException: The UNC path should be of the form \server\share.

http://stackoverflow.com/questions/3567063/get-a-list-of-all-unc-shared-folders-on-a-local-network-server

//
// Enumerate shares on local computer
//
Console.WriteLine("\nShares on local computer:");
ShareCollection shi = ShareCollection.LocalShares;
if (shi != null)
{
foreach(Share si in shi)
{
Console.WriteLine("{0}: {1} [{2}]",
si.ShareType, si, si.Path);

// If this is a file-system share, try to
// list the first five subfolders.
// NB: If the share is on a removable device,
// you could get “Not ready” or “Access denied”
// exceptions.
if (si.IsFileSystem)
{
try
{
System.IO.DirectoryInfo d = si.Root;
System.IO.DirectoryInfo[] Flds = d.GetDirectories();
for (int i=0; i < Flds.Length && i < 5; i++) Console.WriteLine(“\t{0} – {1}”, i, Flds[i].FullName); Console.WriteLine(); } catch (Exception ex) { Console.WriteLine(“\tError listing {0}:\n\t{1}\n”, si, ex.Message); } } } } else Console.WriteLine(“Unable to enumerate the local shares.”); // // Resolve local paths to UNC paths. // Console.WriteLine(“{0} = {1}”, fileName, ShareCollection.PathToUnc(fileName));

 

8.Serialize De-serialize dynamic objects

Deserialize JSON into C# dynamic object?

http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object

Quick JSON Serialization/Deserialization in C#

 

9.Email attachment

10.OpenXML for excel

https://msdn.microsoft.com/en-us/library/bb448854.aspx

Stylizing https://blogs.msdn.microsoft.com/chrisquon/2009/11/30/stylizing-your-excel-worksheets-with-open-xml-2-0/

Set Column Width https://social.msdn.microsoft.com/Forums/en-US/37419b3b-fc97-47a4-a52f-fba62a9dcabf/how-to-open-an-existing-excel-worksheet-and-set-column-width-to-best-fit-using-openxml-sax-in-c-?forum=oxmlsdk

Open XML SDK: get “Unreadable content” error when trying to populate more than 25 columns

http://stackoverflow.com/questions/14525573/open-xml-sdk-get-unreadable-content-error-when-trying-to-populate-more-than-2

11.Unable to find manifest signing certificate in the certificate store

http://stackoverflow.com/questions/11957295/unable-to-find-manifest-signing-certificate-in-the-certificate-store-even-wh

12. Reflection


public class ObjectB
{
public int Id { get; set; }
public string Name { get; set; }
}

public class ObjectA
{
public int Id { get; set; }
public string Name { get; set; }
public ObjectB Child { get; set; }
}

a. Grap a property of ObjectB obj.GetType().GetProperty(“Name”).GetValue(obj, null);

b. Sum Of a column of generic list by passing column name anonymously List list:list.Sum(x => x.GetType().GetProperty(columnName).GetValue(x, null)).ToString();

c. Get Property Value of Nested Classes

public static class ReflectionHelper
{
public static Object GetPropValue(this Object obj, String propName)
{
string[] nameParts = propName.Split('.');
if (nameParts.Length == 1)
{
return obj.GetType().GetProperty(propName).GetValue(obj, null);
}

foreach (String part in nameParts)
{
if (obj == null) { return null; }

Type type = obj.GetType();
PropertyInfo info = type.GetProperty(part);
if (info == null) { return null; }

obj = info.GetValue(obj, null);
}
return obj;
}
}

13. SMTP

Gmail

pro#1: unable to read data from the transport connection net_io_connectionclosed

change port 465 to 587, EnableSsl = true, The .NET SmtpClient only supports encryption via STARTTLS. If the EnableSsl flag is set, the server must respond to EHLO with a STARTTLS, otherwise it will throw an exception.

pro#2: he SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.

it may not be your code issue but high possibility is that your gmail account may encounter security blocking, simpliest way is to check whether you have rececived an email like this:

gmail_smtp_blocked_signin

then click ‘allowing access to less secure apps

if still cannot , try this https://accounts.google.com/DisplayUnlockCaptcha, unlock it

see more at http://stackoverflow.com/questions/20906077/gmail-error-the-smtp-server-requires-a-secure-connection-or-the-client-was-not

14.Compile error

1.for xml/ config file, some times got “Severity Code Description Project File Line Suppression State Error Invalid token ‘Text’ at root level of document”

right click- properties – Build Action – choose None.

2.Parser Error Message: Only one <configSections> element allowed per config file and if present must be the first child of the root

15.Quartz.Net

TimeZone problem https://forums.asp.net/t/2001087.aspx?Quartz+NET+scheduling+jobs+in+mvc+on+windows+azure

How to create a multi-task Azure Worker Role with Quartz.net

http://knightcodes.com/.net/2016/08/15/xml-configuration-for-quartz-net.html

 

16. RUN PYTHON IN .NET

Running Python script from C# and working with the results https://medium.com/@dpursanov/running-python-script-from-c-and-working-with-the-results-843e68d230e5

http://devcenter.wintellect.com/jrobbins/pdb-files-what-every-developer-must-know

WorkingDirectory

rocessStartInfo start = new ProcessStartInfo();rocessStartInfo start = new ProcessStartInfo();start.FileName = “C:\\Python27\\python.exe”;Console.Write(args.Length);// arg[0] = Path to your python script (example : “C:\\add_them.py”)// arg[1] = first arguement taken from  C#’s main method’s args variable (here i’m passing a number : 5)// arg[2] = second arguement taken from  C#’s main method’s args variable ( here i’m passing a number : 6)// pass these to your Arguements property of your ProcessStartInfo instance
start.Arguments = string.Format(“{0} {1} {2}”,args[0],args[1],args[2]);start.UseShellExecute = false;start.RedirectStandardOutput = true;using (Process process = Process.Start(start)){ using (StreamReader reader = process.StandardOutput) { string result = reader.ReadToEnd(); // this prints 11 Console.Write(result); }}

 

mvc ajax get empty data:
By default, the asp.net mvc does not allow an HTTP GET request with a JSON payload. You need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet as the second parameter to the Json method like following.

return Json(returnObj, JsonRequestBehavior.AllowGet);

 

JSON decoding: Unexpected token: StartArray

the value starts from the exception position should be deserialized as an object, not a string

 

small ticks

int a = 42;
int b = 23;
double result = (double)a / b;
 string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
        Console.WriteLine("RunTime " + elapsedTime);

 

#issues: An asynchronous module or handler completed while an asynchronous operation was still pending

https://stackoverflow.com/questions/28805796/asp-net-controller-an-asynchronous-module-or-handler-completed-while-an-asynchr/28806198

That’s because Task.Factory.StartNew does something dangerous in ASP.NET. It doesn’t register the tasks execution with ASP.NET. This can lead to edge cases where a pool recycle executes, ignoring your background task completely, causing an abnormal abort. That is why you have to use a mechanism which registers the task, such as HostingEnvironment.QueueBackgroundWorkItem.

 

Key Word: Long connection, short connection, connection pool, connection time out,thread safe

DTO, DAO, Repository, ORM,

leaky abstraction,code duplication,abstraction inversion

shows how the data layer fits into a typical application architecture

 

Concerns: resource consuming(frequency of opening/closing connection), too many calculation logic in DB(SP) may cause time out issue, concurrency issue,avoid sharing connections between threads(seems no need to concern this,connection drivers already handle it very well)

leaky abstraction(The SQL language abstracts away the procedural steps for querying a database, allowing one to merely define what one wants. But certain SQL queries are thousands of times slower than other logically equivalent queries. On an even higher level of abstraction, ORM systems, which isolate object-oriented code from the implementation of object persistence using a relational database, still force the programmer to think in terms of databases, tables, and native SQL queries as soon as performance of ORM-generated queries becomes a concern.)

Tools: DB Profile, db connector

Framework:

ORM: ORMLite, Asp.Net Entity Framework, Comparison of object-relational mapping software

Common Data Access Layer: ClownFish MySQL Connector/Net

 

Design Guidelines&Patterns:

Chapter 8: Data Layer Guidelines

Appendix C: Data Access Technology Matrix

Writing a Portable Data Access Layer

Mapping Objects to Relational Databases: O/R Mapping In Detail

Decisions on DAO pattern VS Repository(+unitOfWork) pattern
My previous school assignment was using DAO pattern.
JSP Servlets send http request, controllers process request, forward to other controllers if needed, controllers call delegates which will invoke relevant services,
services call dao(dao interface implemented by daoImpl), dao will do the crud operation.

DAO would be considered closer to the database, often table-centric. Repository would be considered closer to the Domain, dealing only in Aggregate Roots. A Repository could be implemented using DAO’s, but you wouldn’t do the opposite.
–quotes from stackoverflow
Datalayer Decisions (Repository, DAO, Services) in Domain-Driven-Design Applications

 

DB Features:

MongoDB: Support asynchronous connection

 

references:

SQL Server Connection Pooling (ADO.NET)

Go’s Connection Pool, Retries, and Timeouts

ClownFish:比手写代码还快的通用数据访问层

some misunderstanding and arguments:

DAO vs ORM(hibernate) pattern

Target:http://reg.***.com/

Crack Process demonstrated by GIF:

crack ** site reg location by LIU YUE
crack ** site reg location by LIU YUE

registration


document.domain = "**.com";
var imwebReg = {ver: 10016,inited: !1,isSeaPhone: $("imweb_phoneArea") ? !0 : !1,switchToSeaPhone: !1,cellphone: "",checkPhoneMap: {},phoneCheck_clock: 0,defaultValue: {countryId: "1",provinceId: "11",cityId: "1",country: "China",province: "Beijing",city: "Dongcheng",yearType: "0",year: "0",month: "0",day: "0"},key:
********************************************************
********************************************************
setTimeout(function() {
$.http.loadScript(imwebReg.url.ver + "?v=" + Math.random())
}, 1E3);
document.body.onmouseover = function() {
imwebReg.init();
document.body.onmouseover = null
};
function initLocation(a) {
imwebReg.loadLocation(a)
}

 

http://*****/iframe/0/en/js/location_en.js

initLocation({AFG:{n:"Afghanistan","0":{n:"",HEA:{n:"Herat"},KBL:{n:"Kabul"},KDH:{n:"Kandahar"},MZR:{n:"Mazar-iSharif"}}},ALA:{n:"Alandlslands","0":{n:"","0":{n:""}}},ALB:{n:"Albania","0":{n:"",BR:{n:"Berat"},DI:{n:"Diber"},DR:{n:"Durres"},EL:{n:"Elbasan"},FR:{n:"Fier"},GJ:{n:"Gjirokaster"},KO:{n:"Korce"},KU:{n:"Kukes"},LE:{n:"Lezhe"},SH:{n:"Shkoder"},TR:{n:"Tirane"},VL:{n:"Vlore"}}},DZA:{n:"Algeria","0":{n:"",ADR:{n:"Adrar"},ADE:{n:"AinDefla"},ATE:{n:"AinTemouchent"},ALG:{n:"Alger"},AAE:{n:"Annaba"},
BAT:{n:"Batna"},BEC:{n:"Bechar"},
********************************************************************************
*********************************************************************************
,MV:{n:"Masvingo"},MN:{n:"Matabeleland North"},MS:{n:"Matabeleland South"},MD:{n:"Midlands"}}}});

$.http.loadScript(imwebReg.url.location);

I decide to export all location data as sql script

first, get json data:

tencent registration

tencent registration

TIPS:
convert string and json format might be tricky, remember replace double quotes with \” before conversion.

by digging into data structure,
Here is my code snippets to generate sql script from the data

$.each(countryList, function(key, country) {

if (country.hasOwnProperty('n')&&country['n']!=null&&country['n']!=undefined&&country['n']!='') {
var countryCode='NULL';
var provinceCode='NULL';
var cityCode='NULL';
var countryName='NULL';
var provinceName='NULL';
var cityName='NULL';

countryCode=key;
countryName=country['n'];
$.each(country,function(key,province){
if(province.hasOwnProperty('n')&&province['n']!=null&&province['n']!=undefined&&province['n']!=''){
provinceCode=key;
provinceName=province['n'];
$.each(province,function(key,city){
if(city.hasOwnProperty('n')&&city['n']!=null&&city['n']!=undefined&&city['n']!=''){
cityCode=key;
cityName=city['n'];
}
if(key!='n'){
console.log("insert into locationEN(countryCode,provinceCode,cityCode,country,province,city) values("+countryCode+","+provinceCode+","+cityCode+","+countryName+","+provinceName+","+cityName+")");
}
});
}else{
if(key!='n'){
console.log("insert into locationEN(countryCode,provinceCode,cityCode,country,province,city) values("+countryCode+","+provinceCode+","+cityCode+","+countryName+","+provinceName+","+cityName+")");
}
}
});
}
});

signalr error

chat room version 1.0 functionality demonstration by gif:

chat room by LIU YUE
chat room by LIU YUE

1.Planning

(all the domains below are fictional)

Now I have a web site website.com, an Oauth2 server oauth.com, and an API server/Resource server api.com,access restricted through oauth only, now I am asked to create an online chatting room for website.com, which will be embedded in website.com using iframe, assume domain is chatroom.com.

General workflow will be: user log on website.com through oauth.com, on oauth successfully website.com pass access_token to chatroom.com, then last step, chatroom use access_token to retrieve user info from API.com, this process is also considered as logon chatroom.

My colleague suggests me to use signalr, compare to super socket, it’s much more easy to draw UI because UI for such an online chatting room is very complicated, another advantage of signalr is that it supports long-polling, means those browsers not supporting websocket will also works fine, while the disadvantage is I need to maintain my own ‘sessions’, signalr or most web sockets do not support session feature by default.( why? answer in my blog ‘About Session‘ )

2.Business Modeling

– Domain Modeling ( use case driven approach,the task of discovering ‘objects’ that represent those business entities and concepts)

User(name,online status)

Friends

Conversation Room — chat group (name, creator,members,status)

Message — Private Message, Group Message

Recently chat list

3.Requirements

when user successfully connected with server,If he doesn’t have nickname yet, required to update user info through api.com.

after checking nickname, he will be auto assigned to one of the lobbies(system setting channels);

user can switch channels, can check users online status and add friends,

start private conversation with friends,

create chat group with selected friends,manage chat group, invite friend, kick out member.

system will keep track of users’ recently chat records,

missed messages will push to user as soon as he get online.

4.Analysis & Design

1.Tech

MVC for presentation layer

SignalR for communication layer

Mongodb for db layer

2.Detail

user persistence: session

security: form authentication

 

5.implement

Logic:

signalr reconnect?

rejoin room ? missed message push?

session lost handling? token expired handling?

fallback handling,go back to client side, ask for new token ?

performance enhancement?

code refactor?

 

UI:

Show Loading tips before enter/switch room and disable page event

 

Technical:

1.signalR life cycle

SignalR connection OnConnected OnReConnected OnDisconnected

Transport connection

negotiate –> connect –> start–> send….—> reconnect

(reconnect every 5s,on 30s throw hub error:

Error: Couldn’t reconnect within the configured timeout of 30000 ms, disconnecting. {source: “TimeoutException”, stack: (…), message: “Couldn’t reconnect within the configured timeout of 30000 ms, disconnecting.”}

Error: The client has been inactive since Wed May 13 2015 15:27:25 GMT+0800 (China Standard Time) and it has exceeded the inactivity timeout of 50000 ms. Stopping the connection. {source: “TimeoutException”, stack: (…), message: “The client has been inactive since Wed May 13 2015…ity timeout of 50000 ms. Stopping the connection.”}

), then abort (check network)
$.signalR.connectionState
Object{connecting:0, connected:1, reconnecting:2, disconnected:4}
error: connect before call

solution: block user before connected,e.g. using overlap loading.

2. send failed error

ChatHub.Send failed:
chatroom.js:351 Error: Error: Send failed.
at Object.r._.error (http://chatroom.24popcorn.com/Scripts/jquery.signalR-2.2.0.min.js:8:4512)
at i.l (http://chatroom.24popcorn.com/Scripts/jquery.signalR-2.2.0.min.js:8:34125)
at Object.<anonymous> (http://chatroom.24popcorn.com/Scripts/jquery.signalR-2.2.0.min.js:8:35652)
at Object.<anonymous> (http://chatroom.24popcorn.com/Scripts/jquery.signalR-2.2.0.min.js:8:11987)
at Object.n.event.dispatch (http://chatroom.24popcorn.com/Content/js/jquery-latest.min.js:3:8066)
at Object.r.handle (http://chatroom.24popcorn.com/Content/js/jquery-latest.min.js:3:4774)
at Object.n.event.trigger (http://chatroom.24popcorn.com/Content/js/jquery-latest.min.js:3:7167)
at n.fn.extend.triggerHandler (http://chatroom.24popcorn.com/Content/js/jquery-latest.min.js:3:15006)
at s (http://chatroom.24popcorn.com/Scripts/jquery.signalR-2.2.0.min.js:8:18319)
at Object.u.ajax.success (http://chatroom.24popcorn.com/Scripts/jquery.signalR-2.2.0.min.js:8:18593)
chatroom.js:118 SignalR error: Error: Send failed.
chatroom.js:662 ChatHub.Send failed:
chatroom.js:663 Error: Connection was disconnected before invocation result was received.
at Object.r._.error (http://chatroom.24popcorn.com/Scripts/jquery.signalR-2.2.0.min.js:8:4512)
at i.l (http://chatroom.24popcorn.com/Scripts/jquery.signalR-2.2.0.min.js:8:34125)
at f (http://chatroom.24popcorn.com/Scripts/jquery.signalR-2.2.0.min.js:8:32687)
at Object.<anonymous> (http://chatroom.24popcorn.com/Scripts/jquery.signalR-2.2.0.min.js:8:35854)
at Object.<anonymous> (http://chatroom.24popcorn.com/Scripts/jquery.signalR-2.2.0.min.js:8:12085)
at Object.n.event.dispatch (http://chatroom.24popcorn.com/Content/js/jquery-latest.min.js:3:8066)
at Object.r.handle (http://chatroom.24popcorn.com/Content/js/jquery-latest.min.js:3:4774)
at Object.n.event.trigger (http://chatroom.24popcorn.com/Content/js/jquery-latest.min.js:3:7167)
at n.fn.extend.triggerHandler (http://chatroom.24popcorn.com/Content/js/jquery-latest.min.js:3:15006)
at Object.r.fn.r.stop (http://chatroom.24popcorn.com/Scripts/jquery.signalR-2.2.0.min.js:8:13160)

reason:another asynchronous call still in processing, may cause dead lock

solution:

queue before send calling, using Jquery.defferred Promise

http://stackoverflow.com/questions/17308172/deferred-versus-promise

http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/

http://www.vasanthk.com/jquery-promises-and-deferred-objects/

signalr error

invalid-operation-exceptioninvalid-operation-exception-req

Finally!!! Let’s meet the murderer !!!

[InvalidOperationException]: An asynchronous module or handler completed while an asynchronous operation was still pending.

http://stackoverflow.com/questions/17659603/async-void-asp-net-and-count-of-outstanding-operations
Regarding “fire and forget”:
I personally never use this phrase for async void methods. For one thing, the error handling semantics most certainly do not fit in with the phrase “fire and forget”; I half-jokingly refer to async void methods as “fire and crash”. A true async “fire and forget” method would be an async Task method where you ignore the returned Task rather than waiting for it.
That said, in ASP.NET you almost never want to return early from requests (which is what “fire and forget” implies). This answer is already too long, but I have a description of the problems on my blog, along with some code to support ASP.NET “fire and forget” if it’s truly necessary.

http://www.wiliam.com.au/wiliam-blog/async-void-dont-use-it
https://msdn.microsoft.com/en-us/magazine/jj991977.aspx

3.query in MongoDB using C# Driver

http://stackoverflow.com/questions/24169849/searching-an-array-of-objects-in-mongodb-using-the-c-sharp-driver

http://stackoverflow.com/questions/5457637/mongodb-field-array-searching-c-how-to?rq=1

http://stackoverflow.com/questions/25727553/querying-an-array-of-arrays-with-the-mongodb-c-sharp-driver?rq=1

4.httpcontext session/cookie is null with IE

You can try the following code by adding in Global.asax file

protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader(“p3p”, “CP=\”CAO PSA OUR\””);
}
The problem lies with a W3C standard called Platform for Privacy Preferences or P3P. This will allow Internet Explorer to accept your cookie. You will need to send the header on every page that sets a cookie.

5.Page refresh, SignalR disconnect and connect again and assign new connectionID, but how to maintain state(First Connection Time and current conversation state)

http://kevgriffin.com/maintaining-signalr-connectionids-across-page-instances/

solution: Maitain your own SessionList, OnDisconnected mark check session state, if previous online=true, set online=false and remove connectionID from , else remove session, when OnConnected check session, if find user in session and previous online=false, set it true, and add new connectionID

6.Configuration Management

release maintenance

 

 

CookieAuthenticationSample

Using ajaxSetup beforeSend for Basic Auth is breaking SignalR connection

2.detail

Understanding and Handling Connection Lifetime Events in SignalR

 

emoticon

 

video:

resources:

Emoticons (Verify Code e4d6) 聊天表情源码 提取码 e4d6

7.Continuous Integration

another system which is the back end system need to interact with chatroom, e.g. from back end system, admin can ‘push’ messages to all clients connected with chatroom,

back end system was implemented using .net c# technology,

issues: I am using Form Authenticate with ChatHub which is the only hub I have so far. JS Clients connect to it after authentication.

solution: add one more hub to interact with .net client, this new hub need also keep reference of ChatHub to notify all JS Clients connected to it.

http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-server#callfromoutsidehub

http://henriquat.re/server-integration/signalr/integrateWithSignalRHubs.html

 

errors encountered:

signalr Unexpected character encountered while parsing value: <. Path ”, line 2, position 1.

reason: failed to connect to the hub, check whether you called the correct path or is there any authentication requires towards your hub.

b.further more, I was asked to make the ‘push’ message be periodic, so I decided to use timer, soon I found the issue, I cannot do async operations inside a timer(threading timer)

solution in my the other blog Code Snippets Series – C#

 

Debug:

websocket_frames[box title=”SignalR Message Format”]

— http://blogs.microsoft.co.il/applisec/2014/03/12/signalr-message-format/

Messages are serialized as JSON objects and contain metadata about the handlers and the connection as well as payload (i.e. the data to transfer) The following information is included in the messages:

– Hubs (H): Handlers (i.e methods) on the server as well as on the clients are grouped in “Hubs”.
– Method (M): The name of the Handler that will process the message.
– Groups: Clients can be grouped on the servers in “groups” for pub-sub implementation.
– Arguments (A): The actual content to be passed to the hander on the client or on the server.
– Cursor (C): Represents a position in the message stream.
– Index (I): The Id of the handler or Callback.
Hub Message Format

Hub Request format (“send” request)

Data={“I”:index,”H”:”samplingstreaminghub”,”M”:”ConnectToStream”,”A”:[“StreamUri”]}

Hubs messages format (server to client)

– {“C”:”messageId value”, “M”:[{“H”:”HubName”,”M”:”HandlerName”,”A”: [“argument list as json”]}]}

– {“C”:”messageId value”, “G”: [“groupName”],”g”: [“groupName”],”T”:1,
“M”:[{“H”:”HubName”,”M”:”HandlerName”,”A”: [“argument list as json”]}]}

Hub Payloads format (“send” request or inside “M” element of Hub message)

– {“H”:”HubName”,”M”:”HandlerName”,”A”: [argument list as json],                                    “S”:{state as json},”I”:index}
– {“H”:”HubName”,”M”:”HandlerName”,”A”: [argument list as json],”I”:index}
Hub Response examples (“send” response)
– {“I”:”0″,”R”:{“return object as json}}
– {“I”: 0} -> no result
– {“I”: 0, “S”:{“x”:1},”R”:1} –> result
– {“I”: 0, “E”:”This is an error”} –> error
– {“I”: 0, “E”:”This is an error”, “T”: “Some stack trace here”} -> error + stack
The following is a complete list of the messages elements:
Hub Messages:

C – Cursor
M – Messages
T – Timeout (only if true) value is 1
D – Disconnect (only if true) value is 1
R – All Groups (Client groups should be reset to match this list exactly)
G – Groups added
g – Groups removed

Hub payload:

I – Callback Operation index
H – Hub name
M – method name
A – arguments
S – state (if not null)

Hub Method return value:

I – Operation index
R – Result
S – State
E – Error
T – stack trace
D – Error Data

The cursor mechanism
As described above the message contains a cursor for identifying the location in the stream. A cursor represents where a particular client is in an infinite stream of messages. If the client disconnects and then reconnects, it asks the OI streaming API for any messages that arrived after the client’s cursor value. The same thing happens when a connection uses long polling. After a long poll request completes, the client opens a new connection and asks for messages that arrived after the cursor.

To find more information download the signalR source code from github. To find the message format just search for json serialization attributes (by searching for “M” for example).

[/box]

 

reference:

MongoDB:

High Performance Search using MongoDB and ASP.NET MVC

Authentication:

Storing Custom Data in Forms Authentication Tickets

form authentication timeout not working

Authentication with SignalR and OAuth Bearer Token

Set Context User Principal for Customized Authentication in SignalR

Session:

Real-time User Notification and Session Management with SignalR

UI:

jQuery plugin to style emoticons with pure CSS3 properties (no images)

Open sourcing Twitter emoji for everyone

jquery.qqFace.js

纯JS+MVC 打造Web实时聊天室

 

relevant question:

How to do forms authentication with SignalR (separate domains)?

SignalR 2.0 in VS2012 registration and Dependency Injection

Passing and verifying the OWIN Bearer token in Query String in WebAPI

Web API / OWIN, SignalR & Authorization

Unable to Identify User Context in SignalR hub decorated with “Authorize” attribute

Context.User is Null on [Authorized] SignalRHub Task OnDisconnected

Integrating SignalR with existing Authorization

How do I authorize access to ServiceStack resources using OAuth2 access tokens via DotNetOpenAuth?

JSON Web Token in ASP.NET Web API 2 using Owin

 

【打破砂鍋系列】SignalR傳輸方式剖析 http://blog.darkthread.net/post-2013-12-03-inside-signalr-transport.aspx

A chatroom for all! http://blogs.msdn.com/b/cdndevs/archive/2014/09/04/node-js-tutorial-series-a-chatroom-for-all-part-1-introduction-to-node.aspx

 

emotion_icon

emotion source(partial):

[{"phrase":"[微笑]","type":"face","url":"/emotion/5c/huanglianwx_org.gif","hot":false,"common":true,"category":"","icon":"/emotion/5c/huanglianwx_thumb.gif","value":"[微笑]","picid":""},{"phrase":"[嘻嘻]","type":"face","url":"/emotion/0b/tootha_org.gif","hot":false,"common":true,"category":"","icon":"/emotion/0b/tootha_thumb.gif","value":"[嘻嘻]","picid":""},{"phrase":"[哈哈]","type":"face","url":"/emotion/6a/laugh.gif","hot":false,"common":true,"category":"","icon":"/emotion/6a/laugh.gif","value":"[哈哈]","picid":""},{"phrase":"[可爱]","type":"face","url":"/emotion/14/tza_org.gif","hot":false,"common":true,"category":"","icon":"/emotion/14/tza_thumb.gif","value":"[可爱]","picid":""}]

download icons to local using c# webclient:
The DownloadFileAsync/DownloadFileCompleted members of WebClient use the Event-based Asynchronous Pattern. If you want to use async and await, you should be using the Task-based Asynchronous Pattern.
In this case, you should use the DownloadFileTaskAsync member, as such(Please note that your Context.listOfLocalDirectories.Add and Errors.printError methods should be threadsafe.):

private async Task DownloadFileAsync(DocumentObject doc)
{
try
{
using (WebClient webClient = new WebClient())
{
string downloadToDirectory = @Resources.defaultDirectory + value.docName;
webClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
await webClient.DownloadFileTaskAsync(new Uri(value.docUrl), @downloadToDirectory);

//Add them to the local
Context.listOfLocalDirectories.Add(downloadToDirectory);
}
}
catch (Exception)
{
Errors.printError("Failed to download File: " + value.docName);
}
}

private async Task DownloadMultipleFilesAsync(List doclist)
{
await Task.WhenAll(doclist.Select(doc => DownloadFileAsync(doc)));
}

emotion.js:

/**
* Doc emotions
* @author LIU YUE
*/

//customize hashtable
function Hashtable() {
this._hash = new Object();
this.put = function(key, value) {
if (typeof (key) != "undefined") {
if (this.containsKey(key) == false) {
this._hash[key] = typeof (value) == "undefined" ? null : value;
return true;
} else {
return false;
}
} else {
return false;
}
}
this.remove = function(key) { delete this._hash[key]; }
this.size = function() { var i = 0; for (var k in this._hash) { i++; } return i; }
this.get = function(key) { return this._hash[key]; }
this.containsKey = function(key) { return typeof (this._hash[key]) != "undefined"; }
this.clear = function() { for (var k in this._hash) { delete this._hash[k]; } }
}

var emotions = new Array();
var categorys = new Array();
var uPeterEmotionsHt = new Hashtable();

$(function () {
var emotionsource="/content/js/" + "emotion_source.js"+ "?v=" + Math.random();
setTimeout(function () { $.getScript(emotionsource)}, 1E3);
});

function AnalyticEmotion(s) {
if(typeof (s) != "undefined") {
var sArr = s.match(/\[.*?\]/g);
if (sArr != null) {
for (var i = 0; i < sArr.length; i++) { if (uPeterEmotionsHt.containsKey(sArr[i])) { var src = "/content/image/" + uPeterEmotionsHt.get(sArr[i]); var reStr = "";
s = s.replace(sArr[i], reStr);
}
}
}
}
return s;
}

(function($){
$.fn.PeterEmotion = function(target){
var cat_current;
var cat_page;
$(this).click(function(event){
event.stopPropagation();

var eTop = target.offset().top + target.height() + 15;
var eLeft = target.offset().left - 1;

if($('#emotions .categorys')[0]){
$('#emotions').css({top: eTop, left: eLeft});
$('#emotions').toggle();
return;
}
$('body').append('

');
$('#emotions').css({top: eTop, left: eLeft});
$('#emotions').html('

正在加载,请稍候...

');
$('#emotions').click(function(event){
event.stopPropagation();
});

$('#emotions').html('

');
$('#emotions #prev').click(function(){
showCategorys(cat_page - 1);
});
$('#emotions #next').click(function(){
showCategorys(cat_page + 1);
});
showCategorys();
showEmotions();

});
$('body').click(function(){
$('#emotions').remove();
});
$.fn.insertText = function(text){
this.each(function() {
if(this.tagName !== 'INPUT' && this.tagName !== 'TEXTAREA') {return;}
if (document.selection) {
this.focus();
var cr = document.selection.createRange();
cr.text = text;
cr.collapse();
cr.select();
}else if (this.selectionStart || this.selectionStart == '0') {
var
start = this.selectionStart,
end = this.selectionEnd;
this.value = this.value.substring(0, start)+ text+ this.value.substring(end, this.value.length);
this.selectionStart = this.selectionEnd = start+text.length;
}else {
this.value += text;
}
});
return this;
}
function showCategorys(){
var page = arguments[0]?arguments[0]:0;
if(page < 0 || page >= categorys.length / 5){
return;
}
$('#emotions .categorys').html('');
cat_page = page;
for(var i = page * 5; i < (page + 1) * 5 && i < categorys.length; ++i){ $('#emotions .categorys').append($('' + categorys[i] + ''));
}
$('#emotions .categorys a').click(function(){
showEmotions($(this).text());
});
$('#emotions .categorys a').each(function(){
if($(this).text() == cat_current){
$(this).addClass('current');
}
});
}
function showEmotions(){
var category = arguments[0]?arguments[0]:'默认';
var page = arguments[1]?arguments[1] - 1:0;
$('#emotions .container').html('');
$('#emotions .page').html('');
cat_current = category;
var path = "/content/image/";
for(var i = page * 72; i < (page + 1) * 72 && i < emotions[category].length; ++i){ $('#emotions .container').append($('' + emotions[category][i].name + ''));
}
$('#emotions .container a').click(function(){
target.insertText($(this).attr('title'));
$('#emotions').remove();
});
for(var i = 1; i < emotions[category].length / 72 + 1; ++i){ $('#emotions .page').append($('' + i + ''));
}
$('#emotions .page a').click(function(){
showEmotions(category, $(this).text());
});
$('#emotions .categorys a.current').removeClass('current');
$('#emotions .categorys a').each(function(){
if($(this).text() == category){
$(this).addClass('current');
}
});
}
}
})(jQuery);

function loadSource(data) {
for (var i in data) {
if (data[i].category == '') {
data[i].category = '默认';
}
if (emotions[data[i].category] == undefined) {
emotions[data[i].category] = new Array();
categorys.push(data[i].category);
}
emotions[data[i].category].push({
name: data[i].phrase,
icon: data[i].icon
});
uPeterEmotionsHt.put(data[i].phrase, data[i].icon);
}
}

ref:
http://stackoverflow.com/questions/16514027/download-multiple-files-async-and-wait-for-all-of-them-to-finish-before-executin

the ocean cleanup
the ocean cleanup

16岁时,Boyan曾赴希腊潜水,却失望地发现水中的废弃物甚至比鱼还多。

自此,Boyan开始了长达两年的研究。

在研究的过程中,他发现每年约有8万吨塑料垃圾进入海洋。

目前在海洋中至少有52500亿件塑料制品,其中三分之一集中在臭名昭著的大太平洋垃圾带。

这种塑料污染会逐年持续带来伤害:

环境危机

每年至少100万只海鸟以及一十万海洋哺乳动物,死于塑料污染。

经济投入

从全球来看,美国每年要花至少$13亿用于包括渔业,航运,旅游和海岸线的清洁。美国西海岸花费每年约合$5亿清理自己的海滩。从海滩清除杂物的费用平均为US $1,500和高达US $25,000吨

健康

有毒的化学物质由塑料吸附,增加的上万倍的浓度。进入食物链后,这些持久性有机污染物的生物累积在食物链,导致鱼内部的污染物具有更高浓度,最终进入人体。这些化学物质对健康的影响主要有:癌症,畸形和生殖能力受损。

随着研究Boyan Slat再也坐不住了!

他开始尝试设计各种收集垃圾的模型,例如由两艘大船拖行的巨大耙子。但这一创意经测试耗资过大,且污染严重,因此作罢。

失败并没有困扰Boyan Slat,使命感召唤着这个1994年出生的年轻人。

 

终于,在19岁时,Boyan Slat提出“巨型漏斗”装置概念用以拦截和清理海洋白色污染。这一守株待兔的设备凭借洋流运动运转,因此可以节省昂贵的燃料费用,也可避免燃料污染。Boyan在网站上解释称:“与其浪费燃料追着垃圾跑,不如让垃圾自己跑进我们的装置里。”

 

这个设计大大提高了清理的理论时间,本来要上千年才能彻底清理,现在只要几年时间。

当时所有的零用钱只有200欧元

很快花得精光

于是他试图获得赞助

没人理他

“我记得有一天联系了300家公司,只有一个回应了我。”

他们不相信这个一脸稚气的孩子

竟然要改变整个海洋

“一年前我不确定它能否成功,可是,至少我得去试一试。”

在6个月的修改和测试后,Boyan将“The Ocean Cleanup”项目提交至非盈利民间机构TedXDelft,该机构一直致力于支持和推动令世界更加美好的项目计划。同年,该计划还荣获荷兰代尔夫特科技大学的“最佳工具设计奖”。

 

2013年2月他放弃了自己的航空航天工程的学习,转而开创了The Ocean Cleanup。

2014年6月,他已经领导由一群科学家和工程师组成的百人团队,他的清洁理论设计也已经变成具有技术可行性和经济可行性的方案,用来计划10年内清理半个太平洋。

Boyan经过初步测算,在太平洋垃圾带,用十年时间即可收集70320000公斤的塑料垃圾,清理每公斤垃圾的成本是4.53欧元

仅为现有清理海洋漂浮物垃圾成本的3%。

紧接着众筹募集了接近220万美元,让这个组织进入试点阶段。首个2000M系统预计2016年部署在日本海域。

与此同时,他的前校友们正过着无忧无虑的生活,而少年Boyan,每天至少工作15个小时

“我很久没见到朋友了,他们会调侃我说大学生活多有趣,然而,我却觉得,我现在做的事情,真正在帮助地球。”

 

 

 

Boyan Slat被评为全球最有前途的20个年轻企业家之一(Intel EYE50),并且获得联合国最高环境保护奖的荣誉,2015年,挪威国王陛下授予Boyan青年企业家奖,The Ocean Cleanup也被伦敦设计博物馆认可为年度最佳设计。

改变历史的时刻也许就是一个简单的初心+傻瓜式的乐观,最终爆发的能量会影响到每一个人。

“我一无所有,除了我的项目,我不担心。如果你也想做点什么,那就尽快去做。”

每当聊到环境问题时

人们总是说

太遥远

就让我们的孩子去担心吧

我说:“喂,我就在这里!”

——Boyan Slat

Source: 19岁 他开始拯救地球 如今他改变了人类的历史

0 1980

Git is an open source distributed version control system (DVCS) that can significantly improve the way you work and collaborate on projects. Git allows you to keep a history of the significant changes made to your local files. It can also backup this history through remote hosting services like GitHub.–GitReal

Most of the following contents are more like my mind map rather than a blog, wish can help you some.

git

 Basic Git Command

assume our repository url is git://test.com/repo.git, have two branches:

default branch master and hotfix branch

git clone git://test.com/repo.git   (from default branch)

git config –global user.name “***”

git config –global user.email “***”

git clone -b hotfix –single-branch git://test.com/repo.git
git remote -v
git remote add origin git://test.com/repo.git
git remote set-url origin git://test.com/repo.git

git checkout — folder/
git diff

git show
git reset HEAD (unstage)

git clean -f (remove untracked file: new files,generated files)

git push –set–upstream origin hotfix

git cherry-pick

git stash
git stash list
git stash apply

git push origin hotfix

git branch (-r/-a)

git checkout (-b) master

git fetch / pull
git merge hotfix

git merge –abort

git branch hotfix -d
Basic Branching and Merging https://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

GIT: FETCH AND MERGE, DON’T PULL http://longair.net/blog/2009/04/16/git-fetch-and-merge/

git log

git log –graph –oneline –decorate –all

https://stackoverflow.com/questions/1057564/pretty-git-branch-graphs

https://git-scm.com/book/zh/v1/Git-%E5%9F%BA%E7%A1%80-%E6%9F%A5%E7%9C%8B%E6%8F%90%E4%BA%A4%E5%8E%86%E5%8F%B2

git show –name-only ********

 

git rebase

branch master & develop

commit changes in develop branch ( don’t push!)

switch to master and git pull

switch to develop git rebase master

if got conflict follow instruction, manually resolve it and git add to mark it as resolved and then git rebase –continue

now is good to do merge

 

dll conflicts

git checkout –theirs — Lib/test.dll

git add Lib/test.dll

.git/index.lock’: File exists. http://stackoverflow.com/questions/7860751/git-fatal-unable-to-create-path-my-project-git-index-lock-file-exists

 

determine remote url

git remote show origin

https://stackoverflow.com/questions/4089430/how-can-i-determine-the-url-that-a-local-git-repository-was-originally-cloned-fr

https://help.github.com/articles/adding-a-remote/

 

track remote branch / link local branch to remote

git push -u origin dev

https://www.git-tower.com/learn/git/faq/track-remote-upstream-branch

https://stackoverflow.com/questions/520650/make-an-existing-git-branch-track-a-remote-branch

Understanding Tracking Branches in Git  https://lornajane.net/posts/2014/understanding-tracking-branches-in-git

 

git branch -vv

git worktree add ../master master

example https://git-scm.com/docs/git-worktree

 

echo “**/.idea/*” >> .gitignore
git status
git add .gitignore
git commit -m “ignore idea subfolders”

git reset HEAD~1 –soft https://stackoverflow.com/questions/19859486/how-to-un-commit-last-un-pushed-git-commit-without-losing-the-changes/19859644

 

git submodule update –init

https://kalyanchakravarthy.net/blog/git-discard-submodule-changes/

git push –delete <remote_name> <branch_name>

git branch -d <branch_name>

 

create pull request

How to Git PR From The Command Line https://hackernoon.com/how-to-git-pr-from-the-command-line-a5b204a57ab1

 

tag

git tag

git checkout tags/v1.0.8

submodule

git submodule update –recursive

subtree

fork and pull request

 

Problem

“git -c diff.mnemonicprefix=false -c core.quotepath=false fetch origin”

1.check if in the middle of merge ( resolve conflicts, merge –abort)

2.If you are running git under a file system that is not case sensitive (Windows or OS X) this will occur if there are two branches with the same name but different capitalisation, e.g. user_model_changes and User_model_changes as both of the remote branches will match the same tracking ref. Delete the wrong remote branch (you shouldn’t have branches that differ only by case) and then git remote prune origin and everything should work

The remote end hung up unexpectedly while git cloning

With this kind of error, I usually start by raising the postBuffer size by:
git config –global http.postBuffer 524288000
(some comments below report having to double the value):
git config –global http.postBuffer 1048576000

http://stackoverflow.com/questions/6842687/the-remote-end-hung-up-unexpectedly-while-git-cloning

3. change remote url

4. add tracking

git branch -u origin/branchname

Tips:

1.create .gitignore using vim .gitignore i ESC :wq

2.delete folder git rm (-r folder name)

git clean -f (to remove the untracked changes) and -fd (to also remove untracked directories) http://stackoverflow.com/questions/61212/remove-local-untracked-files-from-my-current-git-branch

        delete by them: git rm path/to/file

3.revert

a.to revert changes made to your working copy : git checkout .

b.to revert changes made to the index which also called as unstage (i.e., that you have added): git reset  (e.g. git reset HEAD index.html)

git reset did a great job of unstaging octodog.txt, but you’ll notice that he’s still there. He’s just not staged anymore. It would be great if we could go back to how things were before octodog came around and ruined the party.

c.to revert a change that you have committed: git revert

4.origin?master?local branch? remote branch? defalut .git/config(auto edit after clone?)

http://git-scm.com/book/en/v2/Git-Internals-The-Refspec

http://stackoverflow.com/questions/2602546/how-do-i-git-fetch-and-git-merge-from-a-remote-tracking-branch-like-git-pu

5.error: Your local changes to the following files would be overwritten by merge: ****** Please, commit your changes or stash them before you can merge.

a.give up all local changes, and force update with latest source from remote

git fetch –all git reset –hard origin/master

b.only discard specific files which have conflicts

git checkout folderName/fileName.ext  (ext: git checkout <branch_name> — <paths>)

c.fetch and merge

d.git stash git stash pop (By default git stash will not stash files for which there are no history. So if you have files which you have not yet added but which would be overwritten or “created” by the merge, then the merge will still block. In that situation, you can use git stash -u to stash uncommitted files)

http://www.cppblog.com/deercoder/archive/2011/11/13/160007.html

6.Merging vs. Rebasing https://www.atlassian.com/git/tutorials/merging-vs-rebasing

7.error: Ref refs/remotes/origin/dev but expected…

git update-ref -d refs/remotes/origin/dev

8.Git still showing deleted files after a commit

If it lists the files under the “to be committed” section, then just proceed with the commit; the files will remain deleted. (Git tracks deletions too, not just changes.)

If it lists the files under the “changed but not updated” section, then you have two options:

a.Undelete them by restoring the version in the index: git checkout path/to/folder

b.Mark them deleted in Git, then commit: git rm -r path/to/folder

9.display Chinese character

git config core.quotepath false

10.How can I determine the URL that a local Git repository was originally cloned from?

If referential integrity has been broken:

git config –get remote.origin.url
If referential integrity is intact:

git remote show origin
When using git clone (from GitHub, or any source repository for that matter) the default name for the source of the clone is “origin”. Using git remote show will display the information about this remote name.

Tutorial

1.18 Branching Out

When developers are working on a feature or bug they’ll often create a copy (aka. branch) of their code they can make separate commits to. Then when they’re done they can merge this branch back into their main master branch.

We want to remove all these pesky octocats, so let’s create a branch called clean_up, where we’ll do all the work:

git branch clean_up

1.19 Switching Branches

Great! Now if you type git branch you’ll see two local branches: a main branch named master and your new branch namedclean_up.

You can switch branches using the git checkout <branch> command. Try it now to switch to the clean_up branch:

git checkout clean_up

1.23 Preparing to Merge

Alrighty, the moment has come when you have to merge your changes from the clean_up branch into the master branch. Take a deep breath, it’s not that scary.

We’re already on the master branch, so we just need to tell Git to merge the clean_up branch into it:

git merge clean_up

Reference:

Git详解之五 分布式Git

Fast Learning TryGit Online

Git School Git Real

Git How To

 

Practice:

[toggle title=”Toggle Title”]

>>>>>>>>>>>>>>>>>>>>>>>>>

git init

git add / commit -m ” / log

create new folder D/dashboard/Git Cmd/NUS/NUS3

$ git clone ‘/D/dashboard/Git Cmd/NUS/NUS2’
Cloning into ‘NUS2’…
done.

$ cd NUS2

$ git checkout 2d69665fdf18cd852e934eb0a4e597d1a0cfc94f
Note: checking out ‘2d69665fdf18cd852e934eb0a4e597d1a0cfc94f’.

You are in ‘detached HEAD’ state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

git checkout -b new_branch_name

HEAD is now at 2d69665… s

$ git checkout master
Previous HEAD position was 2d69665… s
Switched to branch ‘master’
Your branch is up-to-date with ‘origin/master’.

——————————————————————

$ git tag -a rel1 -m “message”

$ git branch rel1-maint

make changes and commit

$ git checkout rel1-maint
Switched to branch ‘rel1-maint’

make changes and commit

$ git checkout master
Switched to branch ‘master’
Your branch is up-to-date with ‘origin/master’.

$ git merge rel1-maint
Auto-merging test.txt
CONFLICT (content): Merge conflict in test.txt
Automatic merge failed; fix conflicts and then commit the result.

open file:

<<<<<<< HEAD
master
=======

branch
>>>>>>> rel1-maint

fix conflict and commit

————————————————————————

$ git remote add origin https://github.com/lyhistory/NUS.git
fatal: remote origin already exists.

$ git remote rm origin

$ git remote add origin https://github.com/lyhistory/NUS.git

$ git push origin master
Username for ‘https://github.com’: lyhistory
Password for ‘https://lyhistory@github.com’:
To https://github.com/lyhistory/NUS.git
! [rejected] master -> master (fetch first)
error: failed to push some refs to ‘https://github.com/lyhistory/NUS.git’
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., ‘git pull …’) before pushing again.
hint: See the ‘Note about fast-forwards’ in ‘git push –help’ for details.

$ git pull https://github.com/lyhistory/NUS.git

$ git push origin master
Username for ‘https://github.com’: lyhistory
Password for ‘https://lyhistory@github.com’:
Counting objects: 8, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (3/3), done.
Writing objects: 100% (6/6), 528 bytes | 0 bytes/s, done.
Total 6 (delta 0), reused 0 (delta 0)
To https://github.com/lyhistory/NUS.git
7332965..35c9abb master -> master

————————————————————————

————————————————————————-

git pull https://github.com/lyhistory/NUS.git

$ git push
fatal: No configured push destination.
Either specify the URL from the command-line or configure a remote repository us
ing

git remote add <name> <url>

and then push using the remote name

git push <name>

————————————————————————————————————-

git clone https://github.com/lyhistory/NUS.git

$ git log
commit 733296510c34b8e6115de7d534d9beef9a711db0
Author: Liu Yue <A0135928@u.nus.edu>
Date: Sat Feb 28 14:59:45 2015 +0800

version 2

commit b13bc594981acf6e0567c1c16de27b9f2876e143
Author: Liu Yue <A0135928@u.nus.edu>
Date: Sat Feb 28 14:57:53 2015 +0800

version 1

commit 2df201ad9f933fd248b47287afa0e7d0c8f38454
Author: Liu Yue <lyhistory@gmail.com>
Date: Sat Feb 28 14:33:59 2015 +0800

Initial commit

×××@CR3549 /Z/test/NUS ((7332965…))
$ git checkout b13bc594981acf6e0567c1c16de27b9f2876e143
Previous HEAD position was 7332965… version 2
HEAD is now at b13bc59… version 1

×××@CR3549 /Z/test/NUS ((b13bc59…))

×××@CR3549 /Z/test/NUS ((b13bc59…))
$ git checkout master
Previous HEAD position was b13bc59… version 1
Switched to branch ‘master’
Your branch is ahead of ‘origin/master’ by 2 commits.
(use “git push” to publish your local commits)

×××@CR3549 /Z/test/NUS (master)
$ git log
commit 733296510c34b8e6115de7d534d9beef9a711db0
Author: Liu Yue <A0135928@u.nus.edu>
Date: Sat Feb 28 14:59:45 2015 +0800

version 2

commit b13bc594981acf6e0567c1c16de27b9f2876e143
Author: Liu Yue <A0135928@u.nus.edu>
Date: Sat Feb 28 14:57:53 2015 +0800

version 1

commit 2df201ad9f933fd248b47287afa0e7d0c8f38454
Author: Liu Yue <lyhistory@gmail.com>
Date: Sat Feb 28 14:33:59 2015 +0800

Initial commit

×××@CR3549 /Z/test/NUS (master)
$

——————————————————————————————————————–

[/toggle]

 

Requesting a pull request review https://help.github.com/articles/requesting-a-pull-request-review/

tools:
git for windows
tortoisegit

reference:

git document

git – the simple guide

Tool: http://sqlfiddle.com/

a mysql db can have many schema,like a building have many rooms, and users can get access to different room, so schema can have more than one user.

SELECT DATE_FORMAT(date_add(date_column,INTERVAL 8 HOUR),'%b %d %Y %h %p'),COUNT(distinct(count_column))
FROM db.table
where date_add(date_column,INTERVAL 8 HOUR) between '2015-02-01 00:00:00' and '2015-03-01 00:00:00'
GROUP BY DATE_FORMAT(date_column,'%b %d %Y %h %p')
order by DATE_FORMAT(date_add(date_column,INTERVAL 8 HOUR),'%b %d %Y %h %p');

 

insert into phoenix.`program-slot`(duration,dateOfProgram,startTime,`weekly-schedule_id`,presenter_id,producer_id,program_id)
select duration,date_add(dateOfProgram,INTERVAL 2 DAY), IFNULL(date_add(startTime,INTERVAL 2 DAY),null) ,100,presenter_id,producer_id,program_id from phoenix.`program-slot` where `weekly-schedule_id` =3
;

 

—————————————————

— Performance on index : when join a large table

—————————————————

bad:

select user.*, log.LoginTime
from users user
left join login_log log on user.id=log.userid and log.LoginTime=(select max(LoginTime) from login_log where userid=log.userid and status=’true’);

good:

select user.*, log.LoginTime
from users user
left join (
select max(LoginTime) LoginTime,userid from login_log
where  status='true'
group by userid) temp on temp.userid=user.userid;


-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE DEFINER=`dbuser`@`%` PROCEDURE `PROCE1`(
in _param varchar(50)
)
root:BEGIN
declare _count int;
select count(1) into _count from table where column=_param;
if _count<>1 then
select -1 as result;
leave root;
end if;

call PROCE2(_param);

do something else

select 0 as result;

END

— ——————————————————————————–
— Routine DDL
— Note: comments before and after the routine body will not be stored by the server
— ——————————————————————————–
DELIMITER $$
CREATE DEFINER=`dbuser`@`%` PROCEDURE `PROCE2`(
in _param int
)
BEGIN
DECLARE done INT DEFAULT FALSE;

declare _variable1 int;
declare _variable2 decimal(10,2);

declare resultCur cursor for select column1,column2 from table where column=_param;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
DECLARE exit handler for sqlexception
BEGIN
ROLLBACK;
get diagnostics condition 1 @p1 = MESSAGE_TEXT;
select -1 as result, @p1 as message from dual;
END;
open resultCur;
operaLoop:Loop
fetch resultCur into _variable1,_variable2;
if done then
leave operaLoop;
end if;

do something…

end Loop;
close resultCur;
END

—————————————————

— Multiple cursors in mysql stored procedure

—————————————————

DROP PROCEDURE IF EXISTS `multipleCursorsAtOne`;
DELIMITER $$
CREATE PROCEDURE `multipleCursorsAtOne`()
BEGIN
DROP TABLE IF EXISTS userNames;
CREATE TEMPORARY TABLE userNames
(userName varchar(200) NOT NULL);

BEGIN
DECLARE done BOOLEAN DEFAULT false;
DECLARE p_first_name VARCHAR(200);
DECLARE cursor_a CURSOR FOR SELECT user_name FROM user_info LIMIT 1,3;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN cursor_a;

cursor_a_loop: LOOP
FETCH cursor_a INTO p_first_name;
IF done THEN
LEAVE cursor_a_loop;
END IF;
— cursor loop statements

IF p_first_name IS NOT NULL AND p_first_name <> “” THEN
INSERT INTO userNames(userName) VALUES(p_first_name);
END IF;
END LOOP;

CLOSE cursor_a;
END;
BEGIN
DECLARE done BOOLEAN DEFAULT false;
DECLARE p_first_name VARCHAR(200);
DECLARE cursor_a CURSOR FOR SELECT user_name FROM user_info LIMIT 4,3;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN cursor_a;

cursor_a_loop: LOOP
FETCH cursor_a INTO p_first_name;
IF done THEN
LEAVE cursor_a_loop;
END IF;
— cursor loop statements

IF p_first_name IS NOT NULL AND p_first_name <> “” THEN
INSERT INTO userNames(userName) VALUES(p_first_name);
END IF;
END LOOP;

CLOSE cursor_a;
END;

SELECT * FROM userNames;
END
$$

mysql workbench The type initializer for ‘HtmlRenderer.Utils.FontsUtils’ threw an exception.

http://stackoverflow.com/questions/32020024/upgrading-to-windows-10-breaks-mysql-workbench

https://bugs.mysql.com/bug.php?id=75344

 

script import issue;

delimiter http://buysql.com/mysql/42-delimiter-mysql.html

— Set new delimiter ‘$$’
DELIMITER $$

$$

— Set default delimiter ‘;’
DELIMITER ;

Recursive query

Hierarchical data in MySQL: parents and children in one query

Managing Hierarchical Data in MySQL

 

从昨天到今天经历了大悲大喜,特此吐槽,宣泄一下情感
背景:1年多前在新加坡PC SHOW的Best denki购买了Dell Alienware M14X-R2,pre-install win8 core edition

昨天下午开始,win8突然popup全屏的激活提示窗口,PC SETTING – GO ACTIVATE,我纳闷的点了进去,页面上两个按钮,ACTIVATE 和 ENTER KEY,我点了下activate,结果‘activate failed, try again later’,Error Code 0xC004F074 – No KMS Service is contacted,KMS(KEY MANAGEMENT SERVICE),这么不友好的提示信息,我就百度谷歌了下ksm激活,找到了很多2012年的帖子,先说一下基本命令:

[box title=”slmgr “]
slmgr /ipk x-x-x-x-x 安装产品密钥,也可以说是替换现有密钥,就是那个5x5的序列号product key。
slmgr /skms x.x.x.x 设置KMS服务器IP地址及端口。
slmgr /ato 尝试在线激活Windows。
slmgr.vbs -dlv 显示详细的激活信息,包括:系统版本、激活ID、安装ID、部分产品密钥、许可证状态、剩余 Windows 重置计数等。
slmgr.vbs -xpr 查看当前许可证状态的截止日期,同样我们可以用它来检查Windows是否是永久激活
slmgr.vbs -cpky 从注册表中清除产品密钥信息,这是一项安全举措,清除之后那些声称读取产品密钥的软件就读不到了。
slmgr.vbs -ilc 导入OEM证书,后面为OEM证书的路径。
slmgr.vbs -upk 卸载当前产品密钥,重启电脑之后系统将重归未激活状态,会出现输入密钥和联网激活界面

[/box]

首先我们要有product key,可以用product key viewer[下载]查看本机的product key,然后还有一个重点是重设KMS服务器IP地址和端口,这个我在网上找了好几个ip都失败了,提示‘KMS can’t contact*****’,(事后我找到了几个2014年最新的WIN8和win8.1 KMS激活工具,声明我没用这种方法,所以不知道效果,需要可以联系我)
我又尝试了下输入我通过那个product key查看工具获取的本机product key,同样无效,提示‘this product key not work’

我折腾了半天,突然想了下,我的机器本身预装的就是正版系统,然后我是购买不久后升级到了win8.1(free upgrade),没理由1年后提示我又要激活!!!怀着疑问,我电话求助best denki售后,新加坡的售后服务比不上天朝,个人观点,这边大多人对工作抱怨很多,没有像天朝即使拿着几千块工资一样热情高涨的情况,接电话的售后也算还好,告诉我去联系dell,关于windows技术问题他们也不懂,我搜索了下,在dell官网新加坡site只看到了1开头的一组号码,都是美国的,新加坡太小,客服都由老美包办了,打了两个不通,有一个说了半天没有人工,我的机器是全球保修,我立马转向天朝,天朝的一个售后mm接了电话,大概了解情况后,给我说了两个方法:1.还原系统回到win8 2.打电话给微软电话激活
我先用了2,mm给的是国内的微软服务中心4008203800,然后对方告诉我联系微软电话激活4008301832,对方告诉我win+r输入 slui 4 的命令,结果弹出‘cannot activate windows by phone’,这个帅哥也不懂为啥,让我打回先前的电话,沟通了一番,他们给我找到了新加坡的微软服务中心(8008523543 60377124671),我电话过去,对方说 are you calling from Singapore?我才知道原来也不是新加坡的,估计不是美国就是马来西亚,这个aunty让我同样输入slui 4的命令,我告诉她做过了,然后她让我去激活页面找一个电话激活的一个序列号,我告诉她激活页面根本没有那个option,只有两个按钮,aunty恍然大悟’oh, i c, you need to go back to your oem, you ask them to activate your machine with oem production key******’,我告诉她我刚在网上用一个软件找到了oem product key,她告诉我’i understand you have the key,but you need to ask the oem activate it as administrator.’,我立即又联系best denki和dell,各种不爽之后,我决定尝试一下自己的想法,最终证明我是对的!

刚才通话时我提到oem的product key是用这两个软件查到的:
RWEverything
AIDA64[下载]
AIDA64 Extreme Edition(至尊版):
ULUG1-PRWD6-U8DA7-8DMM4-FUYR8FW4E4-J3UD6-25DG9-5D8S4-UWADB3Z3TD-7UDD6-K7DGB-CDPN4-F6K9E
AIDA64 Business Edition(商业版):
3NB91-34VD6-1ADG4-3DPLY-TM1PUU3JX4-JF4DB-WBDAF-8DMNY-98ZJ63L6F1-LUPD6-CVDGX-ZDPFY-TNCJM3R6EY-83ED6-JFDGT-GD2MY-TCJWL339JY-AFUDB-37DAH-TD28Y-TXEC1

AIDA64 支持Win8.1正式版
AIDA64 支持Win8.1正式版

最后发现解决问题的还是最初我发现的这个帖子Windows 8.1 Activation – Error Code 0xC004F074 – No KMS Service is contacted,只是当时我没有这么去做,还好那个好心的aunty告诉我这个版本是oem版本,所以我才确定直接用oem product key激活(在windows激活页面选择‘enter key’更换密钥),等待了十几秒,windows结果‘you done the activation’,赶紧去system查看,‘windows is activated’,如释重负,不用重装系统了,不用还原了,我的机器可是装备了各式武器,小至av制作等瑞士军刀(笑,各种视频图片处理专业软件)大到开发级重量武器,重装一遍很痛苦。

 

总结,系统软件问题还真指望不上所谓的技术支持,微软中国美国新加坡的客服中心以及dell售后的知识储备和岗位培训严重滞后!不能责怪best denki 他们也是一无所知,只知道卖产品!!

参考资料(说明,下面的参考资料只是我解决问题过程中搜索到的一些页面,里面提到的方法并没有全部尝试,请慎用):
Obtaining your OEM BIOS Embedded SLP Product Key using RW-Everything (Windows 8.0/8.1 OEM Only)
Slmgr.vbs Options
DELL SUPPORT
bestdenki singapore

How to troubleshoot the Key Management Service (KMS)

Windows 8超简单激活 – KMS傻瓜式激活,亲测完美!
预装Win8/8.1电脑重装系统利用电脑内置密钥自动激活操作注意事项 v2.1
KMSpico 10.0.4 | 知名KMS激活神器

RANDOM POSTS

0 2433
Lee Kuan Yew: Founder Of The Nation Time Nor Tide, Remembering Lee Kuan Yew Part 1 Part 2 rememberingleekuanyew channelnewsasia rememberingleekuanyew