Saturday, December 26, 2015

Task VS Thread

Threads run in a shared memory space


Processes run in separate memory spaces. each process has its own memory space and at least 1 thread, know as primary thread.

Thread
  1. Able observe its state. (specify name for debugging, Show in UI)
  2. Able to set thread-level properties (stack size, apartment state, or culture)
  3. Maintain an object owned by a single thread. ( Only used by that thread)
  4. Problem : costly, Each thread consumes a non-trivial amount of memory for its stack

ThreadPool
  1. Is a wrapper around a pool of threads, no create its own OS thread.
  2. Use for Short Operations & no result return.
  3. Use to avoid overhead of creating too many threads. 
  4. Able to execute at some point.
  5. Able control the size of the pool, 
  6. Not able to tell the pool start running the work.
  7. It will full , if too many long-running tasks.
  8. Not able to get the result (which item has been completed.)
Task
  1. Is lightweight object for managing a parallelizable unit of work. (work something in Parallel).Parallel means the work is spread across multiple processors to maximize computational speed.
  2. Does not create its own OS thread.(Executed by a TaskScheduler, run on threadPool)
  3. Unlike the ThreadPool, Task able to find out when it finishes, to return a result.
  4. Call ContinueWith() to run more code once the task finishes, and pass you the task's result.
  5. Call Wait() to synchronously wait for a task to finish. Like Thread.Join(), this will block the calling thread until the task finishes. Synchronously waiting for a task is bad idea; it prevents the calling thread from doing any other work, and lead to deadlocks if the task ends up waiting (even asynchronously) for the current thread.
  6.  Parallel.For*() methods, PLINQ, C# 5 await, and modern async methods in the BCL, are all built on Task.
Conclusion
Task is almost always the best option; it provides a much more powerful API and avoids wasting OS threads.

Sunday, December 20, 2015

Task vs parallel

Parallel is faster than Task.

Task
task = new Task(() => DoSomething());
task.Start();
task.Wait();

------------------

Action action = new Action(() => SendSMSAsync(DoSomething()));

Parallel.Invoke(action);   

Sunday, December 13, 2015

Run application in cmd

cmd : start "" d:\applicationfolder\application.exe

Write REST Web API

Attribute routing - More Control the Web API URL.

URL : /customers/1/orders
[Route("customers/{customerId}/orders")]
public IEnumerable<Order> GetOrdersByCustomer(int customerId) { ... }
(1)Enabling Attribute Routing 
(2)Convention-based
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Attribute routing.
        config.MapHttpAttributeRoutes();  (1)

        // Convention-based routing.
        config.Routes.MapHttpRoute(        (2)
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}



Tuesday, December 8, 2015

Web Request

string url = "PenyuApi.aspx?user=" + user + "&pass=" + pasword;

WebRequest request = WebRequest.Create(url);
request.Timeout = 30000; //5 sec call
WebResponse response = request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string Contents = stream.ReadToEnd();

Wednesday, September 9, 2015

Queue and Service Broker

Find db Users
SELECT * FROM sys.database_principals

Find Permission 
SELECT * FROM sys.database_permissions WHERE grantee_principal_id = 5

Create Queue and Service Broker
CREATE QUEUE PricesMessage;
CREATE SERVICE PricesNotifications
ON QUEUE PricesMessage
([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]);

Grant Access For Queue (only run 1 time for all Queue 
GRANT RECEIVE ON QueryNotificationErrorsQueue TO dbadmeen;
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO dbadmeen;
GRANT REFERENCES ON CONTRACT::[http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification] TO dbadmeen;

Grant Access For Queue and ServiceBroker (Run for every queue and service) 
GRANT SEND ON SERVICE::[PricesNotifications] To dbadmeen;
GRANT RECEIVE ON [dbo].[PricesMessage] TO dbadmeen;
-- for user to see the services
GRANT VIEW DEFINITION ON SERVICE::[PricesNotifications] to dbadmeen;

****
Disable Queue & Enabale Queue
alter database dbName set disable_broker with rollback immediate;
alter database dbName set enable_broker with rollback immediate;

Get all the queue in that DB and numbers of message
SELECT sq.name, p.rows 

FROM sys.service_queues sq Join sys.internal_tables it ON sq.object_id = it.parent_id AND it.parent_minor_id = 0 AND it.internal_type = 201 Join sys.indexes as i on i.object_id = it.object_id and i.index_id = 1 Join sys.partitions as p on p.object_id = i.object_id and p.index_id = i.index_id WHERE sq.object_id = it.parent_id AND it.parent_minor_id = 0 AND it.internal_type = 201

See the queue

Select * From sys.dm_qn_subscriptions

Thursday, September 3, 2015

Rename Column

Use DBName
go


EXEC sp_rename '.dbo.Table.oldColumnName', 'NewColumnName', 'COLUMN'


-NewColumnName no need Tables or any . []

Tuesday, September 1, 2015

WF Errors

Error Message
Literal<Boolean>' is not of type 'Delay'. When loading this instance you must ensure that the activity with name 'Literal<Boolean>

Solve: It might be CorrelationID is null

Sunday, July 19, 2015

Q & A

A. 
It compiles your code into a .NET Assembly
B. 
It provides access to Microsoft’s library of code
C. 
It provides a common type system for your application
D. 
It is what your program runs inside of ... it protects the user from malicious code, and handles memory management and other runtime tasks
A. 
A block of code
B. 
A method
C. 
A function
D. 
A variable
A. 
A way to restrict access to your code
B. 
A named block of code that you can call / execute by calling its name
C. 
A means of organizing your code
A. 
A .NET Package
B. 
A .NET Component
C. 
A .NET
D. 
A .NET Assembly
A. 
An XML that contains project settings and the current state of the project
B. 
A file that contains all the C# code
C. 
A file that contains C# code containing project settings, files to include in the project, etc.
D. 
An XML file that contains information about all the project in a given solution

Monday, June 22, 2015

Find Gridview Row From List and check it.

foreach (var item in listPeople)
{
 var row = gvAddPeople.Rows.Cast<GridViewRow>()
.Where(x => ((HiddenField)x.Cells[0].Controls[3]).Value == item.PeopleID.ToString()).Single();

 ((CheckBox)row.Cells[0].Controls[1]).Checked = true;
}

Monday, June 1, 2015

Advanced LINQ

Get same attribute between 2 List

var listPerson = AlllistPerson.Where(x => listPhone
 .Any(y => x.PersonPhone.Contains(y.PhoneNmbers).ToList();

Remove from another List (duplicate)

var result = personList.Where(c => !transactionList.Exists(b => c.phone == b.phone)).ToList();

Remove from another List (duplicate) & Child List


List<long> phoneNumbers = sessionTelco.SelectMany
                            (x => x.PhoneList.Select(y => y.phone)).ToList();

coveragePrices = coveragePrices.Where(x => ! phoneNumbers.Contains(x. phone)).ToList();

Selecting First Item from every group

var grouped = personList.GroupBy(x => x.CountryName).Select(y => y.First()).ToList();

 var grouped = from x in personList
            group x by x.CountryName
            into y
            select y.First();


select many from child list.


List<long> routeClassIDList = _upc.SessionClientGroupList.SelectMany
         (x => x.ClientGroupCoverageList.Select(y => y.RouteClassID)).ToList();


filter all child list same with list


clientGroups = clientGroups.Where(x => !x.ClientGroupCoverageList.All(y => routeClassIDList.Contains(y.RouteClassID))).ToList();


ForEach Add if else


people.ForEach(x => { if (x.Balance.HasValue == false || x.Balance.Value == 0) x.Balance = null; });


INNER JOIN 
devicePerAccList = (from f in devicePerAccList
                    join s in Accounts on f.AccountId equals s.E2AccountId
                    select new DevicePerAcc
                    {
                        AccountId = f.AccountId,
                        AccCode = s.AccountCode,
                        NoOfDevice = f.NoOfDevice

                    }).ToList();

Select Many, Find Description, Filter Description = null, Order By 1A , 2B , 11A

preBookMealList = ssrReportList.SelectMany(a => a.SSRCodes.Select(b => new PreBookMeal
{
SSRCode = b,
SSRDescription = ssrMealList.Where(c => c.SSRCode == b).Select(d => d.Name).FirstOrDefault()
})
.Where(e => e.SSRDescription != null))
.OrderBy(f => int.Parse(f.SeatNo.Remove(f.SeatNo.Length - 1)))
.ToList();


Dictionary put Key to object ID

result = peopleList.Select(x => { x.Value.peopleID = x.Key; return x.Value; }).ToList();