how to reduce process speed of Entity FrameWork code? - entity-framework-4

I used this code in order to Read & Update a value in database which indicate Pageviews of a website.
void Session_Start(object sender, EventArgs e)
{
intPageView++;
Session.Add("Online", intPageView);
DataLayer.MainFunction.UpdateOnlineUser();
}
public static void UpdateOnlineUser()
{
try
{
int intCount = 0;
TaffyPetEntities db = new TaffyPetEntities();
T_Setting t_s = db.T_Setting.SingleOrDefault(i => i.ID == 1);
intCount = Convert.ToInt32(t_s.Page_counter);
intCount++;
t_s = new T_Setting();
t_s = db.T_Setting.First(i => i.ID == 1);
t_s.Page_counter = intCount;
db.SaveChanges();
}
catch (Exception err)
{
DataLayer.Error.RegisterError("MainFunction.cs", err.Message);
}
}
in local system every thing was good also running speed was good, but when website published and uploaded on the server every thing is changed. The problem is, at the first we haven't any data outout and when you clicked on each link on the website it takes too long to show another page.
to find out problem, i used Performance Analysis of VIsual Studio. at the result page of this analysis i found that this part of above code use 70% of total process:
T_Setting t_s = db.T_Setting.SingleOrDefault(i => i.ID == 1);
The questions is:
1. Is it correct syntax for fetching data in Entity FrameWork at the Data Layer (DAL) of a website?
2. Can i change this code with another method in order to reduce process speed?
Thanks.

Related

Problems detecting collision (Eyeshot) in an array of Tasks

I'm trying to check for each movement in a different task and after checking if there was a collision, in some iterations it generates an Exception "A source matrix was not long or sufficient. Check the index and length, as well as the lower limits of the matrix."
If you try to run sequentially in a "for" the error does not occur, I need to run in parallel to increase performance.
In debugging tests I notice that the error always occurs when trying to run cd.DoWork()
private void btn_Tasks_Click(object sender, EventArgs e)
{
// The source of your work items, create a sequence of Task instances.
Task[] tasks = Enumerable.Range(0,tabelaPosicao.Count).Select(i =>
// Create task here.
Task.Run(() =>
{
VerifiCollision(i);
})
// No signalling, no anything.
).ToArray();
// Wait on all the tasks.
Task.WaitAll(tasks);
}
private void VerifiCollision(object x)
{
int xx = (int)x;
int AuxIncrMorsa = Convert.ToInt32(tabelaPosicao[xx].Posicao) * -1;
bRef_BaseMorsa.Transformation = new Translation(0, AuxIncrMorsa, 0);
CollisionDetection cd = new CollisionDetection(new List<Entity>() { bRef_BaseMorsa }, new List<Entity>() { bRef_Matriz }, model1.Blocks, true, CollisionDetection2D.collisionCheckType.OBWithSubdivisionTree, maxTrianglesNumForOctreeNode: 5);
{
if (cd != null)
{
try
{
cd.DoWork();
}
catch (Exception e)
{
e.StackTrace;
}
catch (AggregateException ae)
{
var messege = ae.Message;
}
}
model1.Entities.ClearSelection();
if (cd3.Result != null && cd3.Result.Count > 0)
{
tabelaPosicao[xx].Tuple = new Tuple<string, string>(cd3.Result[0].Item1.ParentName,
cd3.Result[0].Item2.ParentName);
}
}
}
Before applying the transformation you need to clone the entity.
You can have a look at the "WORKFLOW" topic of this article.
I solved it by cloning the Bloks and BlockReference, so each iteration with its transformation performed separately, so there was no possibility that the transformation of one iteration would interfere with another. Grateful for the help.

SWT: Integrate clickable link into StyledText

With the help of this question I was able to figure out how I can display a link inside a StyledText widget in SwT. The color is correct and even the cursor changes shape when hovering over the link.
So far so good, but the link is not actually clickable. Although the cursor changes its shape, nothing happens if clicking on the link. Therefore I am asking how I can make clicking the link to actually open it in the browser.
I thought of using a MouseListener, tracking the click-location back to the respective text the click has been performed on and then deciding whether to open the link or not. However that seems way too complicated given that there already is some routine going on for changing the cursor accordingly. I believe that there is some easy way to do this (and assuring that the clicking-behavior is actually consistent to when the cursor changes its shape).
Does anyone have any suggestions?
Here's an MWE demonstrating what I have done so far:
public static void main(String[] args) throws MalformedURLException {
final URL testURL = new URL("https://stackoverflow.com/questions/1494337/can-html-style-links-be-added-to-swt-styledtext");
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, true));
StyledText sTextWidget = new StyledText(shell, SWT.READ_ONLY);
final String firstPart = "Some text before ";
String msg = firstPart + testURL.toString() + " some text after";
sTextWidget.setText(msg);
sTextWidget.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
StyleRange linkStyleRange = new StyleRange(firstPart.length(), testURL.toString().length(), null, null);
linkStyleRange.underline = true;
linkStyleRange.underlineStyle = SWT.UNDERLINE_LINK;
linkStyleRange.data = testURL.toString();
sTextWidget.setStyleRange(linkStyleRange);
shell.open();
while(!shell.isDisposed()) {
display.readAndDispatch();
}
}
Okay I was being a little too fast on posting this question... There's a snippet that deals with exactly this problem and it shows, that one indeed has to use an extra MouseListener in order to get things working.
The snippet can be found here and this is the relevant part setting up the listener:
styledText.addListener(SWT.MouseDown, event -> {
// It is up to the application to determine when and how a link should be activated.
// In this snippet links are activated on mouse down when the control key is held down
if ((event.stateMask & SWT.MOD1) != 0) {
int offset = styledText.getOffsetAtLocation(new Point (event.x, event.y));
if (offset != -1) {
StyleRange style1 = null;
try {
style1 = styledText.getStyleRangeAtOffset(offset);
} catch (IllegalArgumentException e) {
// no character under event.x, event.y
}
if (style1 != null && style1.underline && style1.underlineStyle == SWT.UNDERLINE_LINK) {
System.out.println("Click on a Link");
}
}
}
});

Fetching gmail emails using .NET MVC

I'm trying to create a little web application to act as a web mail client for Gmail...
I've used the following code to fetch the emails from my inbox:
public ActionResult Index()
{
using (var client = new ImapClient())
{
using (var cancel = new CancellationTokenSource())
{
ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;
client.Connect("imap.gmail.com", 993, true, cancel.Token);
// If you want to disable an authentication mechanism,
// you can do so by removing the mechanism like this:
client.AuthenticationMechanisms.Remove("XOAUTH");
client.Authenticate("********#gmail.com", "****", cancel.Token);
// The Inbox folder is always available...
var inbox = client.Inbox;
inbox.Open(FolderAccess.ReadOnly, cancel.Token);
m = new List<string>();
// download each message based on the message index
for (int i = 0; i < inbox.length; i++)
{
var message = inbox.GetMessage(i, cancel.Token);
m.Insert(i, message.TextBody);
}
client.Disconnect(true, cancel.Token);
}
}
return View(m.ToList());
}
The reason why I dislike this is way of doing is that this part of code:
for (int i = 0; i < inbox.length; i++)
{
var message = inbox.GetMessage(i, cancel.Token);
m.Insert(i, message.TextBody);
}
It takes so long to fetch all the emails, approximately 40 emails are fetched each 5 seconds... So if someone has 2000 emails, it'd take 20 minutes to load all the emails...
Is there any faster way to load all the emails into my MVC application? :/
P.S. I've tried doing it with email which has 10000 emails, and it takes forever to fetch all the emails....
If all you want is the text body of the message, you could potentially reduce IMAP traffic by using the following approach:
var messages = inbox.Fetch (0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure);
int i = 0;
foreach (var message in messages) {
var part = message.TextBody;
if (part != null) {
var body = (TextPart) inbox.GetBodyPart (message.UniqueId, part);
m.Insert (i, body.Text);
} else {
m.Insert (i, null);
}
i++;
}
What this does is send a batched FETCH request to the IMAP server requesting an "outline" (aka body structure) of the message and its unique identifier.
The loop that follows it then looks through the structure of the message to locate which MIME part contains the message's text body and then fetches only that particular sub-section of the message.
In general, you do not watch to download every message over IMAP. The purpose of IMAP is to leave all of the messages on the IMAP server and just fetch the least amount of data possible that you need in order to display whatever it is you want to display to the user.
It should also be noted that you don't actually need to use a CancellationTokenSource unless you are actually planning on being able to cancel the operations.
For example, your code snippet could be replaced with:
public ActionResult Index()
{
using (var client = new ImapClient())
{
ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;
client.Connect("imap.gmail.com", 993, true);
// If you want to disable an authentication mechanism,
// you can do so by removing the mechanism like this:
client.AuthenticationMechanisms.Remove("XOAUTH");
client.Authenticate("********#gmail.com", "****");
// The Inbox folder is always available...
var inbox = client.Inbox;
inbox.Open(FolderAccess.ReadOnly);
m = new List<string>();
var messages = inbox.Fetch (0, -1, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure);
int i = 0;
foreach (var message in messages) {
var part = message.TextBody;
if (part != null) {
var body = (TextPart) inbox.GetBodyPart (message.UniqueId, part);
m.Insert (i, body.Text);
} else {
m.Insert (i, null);
}
i++;
}
client.Disconnect(true);
}
return View(m.ToList());
}
Since you are writing your own webmail front-end to GMail, you may find the following suggestion useful:
When you look at the GMail webmail user interface or Yahoo Mail!'s user interface, you've probably noticed that they only show you the most recent 50 or so messages and you have to specifically click a link to show the next set of 50 messages and so on, right?
The reason for this is because it is inefficient to query the full list of messages and download them all (or even just the text bodies of all of the messages).
What they do instead is ask for just 50 messages at a time. And in fact, they don't ask for the messages at all, they ask for the summary information like so:
var all = inbox.Search (SearchQuery.All);
var uids = new UniqueIdSet ();
// grab the last 50 unique identifiers
int min = Math.Max (all.Count - 50, 0);
for (int i = all.Count - 1; i >= min; i--)
uids.Add (all[i]);
// get the summary info needed to display a message-list UI
var messages = inbox.Fetch (uids, MessageSummaryItems.UniqueId |
MessageSummaryItems.All | MessageSummaryItems.BodyStructure);
foreach (var message in messages) {
// the 'message' will contain a whole bunch of useful info
// to use for displaying a message list such as subject, date,
// the flags (read/unread/etc), the unique id, and the
// body structure that you can use to minimize your query when
// the user actually clicks on a message and wants to read it.
}
Once the user clicks a message to read it, then you can use the message.Body to figure out which body parts you actually need to download in order to display it to the user (i.e. avoid downloading attachments, etc).
For an example of how to do this, check out the ImapClientDemo sample included in the MailKit GitHub repo: https://github.com/jstedfast/MailKit

Twitter4j get followers and following of any user

As a part of my final year project in university I'm analysing Twitter data using graph entropy. To briefly outline the purposes:
I want to collect all tweet from a certain area (London) containing keywords "cold", "flu" etc. This part is done using Streaming API.
Then I want to access each of the user's (who tweeted about being ill, collected in previous section) list of followers and following to be able to build a graph for further analysis. And here I'm stuck.
I assume for the second part I should be using Search API, but I keep getting error 88 even for a single user.
Below is the code I use for the first part:
final TwitterStream twitterStream = new TwitterStreamFactory(cb.build())
.getInstance();
StatusListener listener = new StatusListener() {
public void onStatus(Status status) {
User user = status.getUser();
long userid = user.getId();
String username = status.getUser().getScreenName();
String content = status.getText();
GeoLocation geolocation = status.getGeoLocation();
Date date = status.getCreatedAt();
if (filterText(content)) {
System.out.println(username+"\t"+userid);
System.out.println(content);
System.out.println(geolocation);
System.out.println(date);
try {
getConnections(userid);
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//OTHER LISTENER METHODS
};
twitterStream.addListener(listener);
// London
double lat3 = 51.23;
double lat4 = 51.72;
double lon3 = -0.56;
double lon4 = 0.25;
double[][] bb = { { lon3, lat3 }, { lon4, lat4 } };
FilterQuery fq = new FilterQuery();
fq.locations(bb);
twitterStream.filter(fq);
private static boolean filterText(String tweet) {
return tweet.contains("flu")
|| tweet.contains("cold")
|| tweet.contains("cough")
|| tweet.contains("virus");
}
And this is what I'm trying to complete the second part with:
private static void getConnections(long id) throws TwitterException {
Twitter twitter = new TwitterFactory().getInstance();
long lCursor = -1;
IDs friendsIDs = twitter.getFriendsIDs(id, lCursor);
System.out.println(twitter.showUser(id).getName());
System.out.println("==========================");
do
{
for (long i : friendsIDs.getIDs())
{
System.out.println("follower ID #" + i);
System.out.println(twitter.showUser(i).getName());
}
}while(friendsIDs.hasNext());
}
Any suggestions?
When you receive error 88, that's Twitter telling you that you're being rate limited:
The request limit for this resource has been reached for the current rate limit window.
The search call is limited to either 180 or 450 calls in a 15 minute period. You can see the rate limits here and this documentation explains the rate limiting in detail.
As for how to get around it, you may have to throttle your search calls to the API. Twitter4J provides ways to inspect current limits/exhaustion which may help - see Twitter#getRateLimitStatus().

OData Service not returning complete response

I am reading Sharepoint list data (>20000 entries) using Odata RESTful service as detailed here -http://blogs.msdn.com/b/ericwhite/archive/2010/12/09/getting-started-using-the-odata-rest-api-to-query-a-sharepoint-list.aspx
I am able to read data but I get only the first 1000 records. I also checked that List View Throttling is set to 5000 on sharepoint server. Kindly advise.
Update:
#Turker: Your answer is spot on!! Thank you very much. I was able to get the first 2000 records in first iteration. However, I am getting the same records in each iteration of while loop. My code is as follows-
...initial code...
int skipCount =0;
while (((QueryOperationResponse)query).GetContinuation() != null)
{
//query for the next partial set of customers
query = dc.Execute<CATrackingItem>(
((QueryOperationResponse)query).GetContinuation().NextLinkUri
);
//Add the next set of customers to the full list
caList.AddRange(query.ToList());
var results = from d in caList.Skip(skipCount)
select new
{
Actionable = Actionable,
}; Created = d.Created,
foreach (var res in results)
{
structListColumns.Actionable = res.Actionable;
structListColumns.Created= res.Created;
}
skipCount = caList.Count;
}//Close of while loop
Do you see a <link rel="next"> element at the end of the feed?
For example, if you look at
http://services.odata.org/Northwind/Northwind.svc/Customers/
you will see
<link rel="next" href="http://services.odata.org/Northwind/Northwind.svc/Customers/?$skiptoken='ERNSH'" />
at the end of the feed which means the service is implementing server side paging and you need to send the
http://services.odata.org/Northwind/Northwind.svc/Customers/?$skiptoken='ERNSH'
query to get the next set of results.
I don't see anything particularly wrong with your code. You can try to dump the URLs beign requested (either from the code, or using something like fiddler) to see if the client really sends the same queries (and thus getting same responses).
In any case, here is a sample code which does work (using the sample service):
DataServiceContext ctx = new DataServiceContext(new Uri("http://services.odata.org/Northwind/Northwind.svc"));
QueryOperationResponse<Customer> response = (QueryOperationResponse<Customer>)ctx.CreateQuery<Customer>("Customers").Execute();
do
{
foreach (Customer c in response)
{
Console.WriteLine(c.CustomerID);
}
DataServiceQueryContinuation<Customer> continuation = response.GetContinuation();
if (continuation != null)
{
response = ctx.Execute(continuation);
}
else
{
response = null;
}
} while (response != null);
I had the same problem, and wanted it to be a generic solution.
So I've extended DataServiceContext with a GetAlltems methode.
public static List<T> GetAlltems<T>(this DataServiceContext context)
{
return context.GetAlltems<T>(null);
}
public static List<T> GetAlltems<T>(this DataServiceContext context, IQueryable<T> queryable)
{
List<T> allItems = new List<T>();
DataServiceQueryContinuation<T> token = null;
EntitySetAttribute attr = (EntitySetAttribute)typeof(T).GetCustomAttributes(typeof(EntitySetAttribute), false).First();
// Execute the query for all customers and get the response object.
DataServiceQuery<T> query = null;
if (queryable == null)
{
query = context.CreateQuery<T>(attr.EntitySet);
}
else
{
query = (DataServiceQuery<T>) queryable;
}
QueryOperationResponse<T> response = query.Execute() as QueryOperationResponse<T>;
// With a paged response from the service, use a do...while loop
// to enumerate the results before getting the next link.
do
{
// If nextLink is not null, then there is a new page to load.
if (token != null)
{
// Load the new page from the next link URI.
response = context.Execute<T>(token);
}
allItems.AddRange(response);
}
// Get the next link, and continue while there is a next link.
while ((token = response.GetContinuation()) != null);
return allItems;
}

Resources