Thursday

how to add new Service to reference.svcmap

Add a new MetadataSource into the file, save it, and Update the reference, all metadata files will be downloaded automatically.
MetaSource tag will be looking like this:
  
<MetadataSource Address="http://localhost/myservices/Services/Service1.svc?wsdl" Protocol="http" SourceId="1" />


Sunday

csharp post form data

     
public string POST(string url, string username,string password, string postParams)
{


//Our getVars, to test the get of our php.
//We can get a page without any of these vars too though.
//string getVars = "?var1=test1&var2=test2";
//Initialization, we use localhost, change if applicable
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.UserAgent = GetRndUserAgent();

string Credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));

WebReq.Method = "POST";
WebReq.ContentType = "application/xml";
WebReq.AllowWriteStreamBuffering = true;

WebReq.Headers.Add("Authorization", "Basic " + Credentials);

WebReq.ServicePoint.Expect100Continue = false;



// string postParams = "name=some sort of value";
if (postParams != string.Empty)
{
byte[] buffer = ASCIIEncoding.UTF8.GetBytes(postParams);
WebReq.ContentLength = buffer.Length;
using (Stream writer = WebReq.GetRequestStream())
{

writer.Write(buffer, 0, buffer.Length);

}
}

//From here on, it's all the same as above.
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//Let's show some information about the response
//_log(WebResp.StatusCode.ToString());
//_log(WebResp.Server);

//Now, we read the response (the string), and output it.
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
return _Answer.ReadToEnd();


}

user agent random

     
public static string GetRndUserAgent()
{
string UserAgnet = "";

Random r = new Random();
int i = r.Next(1, 20);

switch (i)
{
case 1:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.34; Windows NT 6.0; WOW64; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30618)";
break;

case 2:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727)";
break;

case 3:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser; .NET CLR 2.0.50727; MAXTHON 2.0)";
break;

case 4:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.1; Media Center PC 3.0; .NET CLR 1.0.3705; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1)";
break;

case 5:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)";
break;

case 6:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; InfoPath.2; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618)";
break;

case 7:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8)";
break;

case 8:
UserAgnet = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en) AppleWebKit/526.9 (KHTML, like Gecko) Version/4.0dp1 Safari/526.8";
break;

case 9:
UserAgnet = "Mozilla/5.0 (Windows; U; Windows NT 5.1; ja; rv:1.9.2a1pre) Gecko/20090402 Firefox/3.6a1pre (.NET CLR 3.5.30729)";
break;

case 10:
UserAgnet = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.8pre) Gecko/20070928 Firefox/2.0.0.7 Navigator/9.0RC1";
break;

case 11:
UserAgnet = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1b4) Gecko/20090423 Firefox/3.5b4 GTB5 (.NET CLR 3.5.30729)";
break;

case 12:
UserAgnet = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/528.16 (KHTML, like Gecko) Version/4.0 Safari/528.16";
break;

case 13:
UserAgnet = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.7pre) Gecko/20070815 Firefox/2.0.0.6 Navigator/9.0b3";
break;

case 14:
UserAgnet = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.2) Gecko/20121223 Ubuntu/9.25 (jaunty) Firefox/3.8";
break;

case 15:
UserAgnet = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.100 Safari/534.30";
break;

case 16:
UserAgnet = "Opera 9.7 (Windows NT 5.2; U; en)";
break;

case 17:
UserAgnet = "Opera/9.64 (X11; Linux x86_64; U; en) Presto/2.1.1";
break;

case 18:
UserAgnet = "Mozilla/5.0 (X11; Linux i686; rv:2.0.1) Gecko/20100101 Firefox/4.0.1)";
break;

case 19:
UserAgnet = "Opera/9.70 (Linux i686 ; U; zh-cn) Presto/2.2.0";
break;

case 20:
UserAgnet = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E; Tablet PC 2.0; MALC)";
break;

default:
UserAgnet = "MMozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0";
break;
}

return UserAgnet;
}

Thursday

Navigation to the webpage was canceled chm

To fix this problem :
Right-mouse click it in Windows Explorer on chm file and select Properties. Then click Unblock.
Here is article describes the how to work around it : http://support.microsoft.com/kb/896054

Wednesday

Strong name validation failed.

To resolve this issue run following command in Visual Studio command line:
sn -Vr "[PathToProblemDLL]\[ProblemDll].dll"


Tuesday

c# extensions

     
//A. allows value.In("one", "two" , "tree")
public static bool In<T>(this T source, params T[] list)
{
if(null==source) throw new ArgumentNullException("source");
return list.Contains(source);
}

//#B Enable quick and more natural string.Format calls
public static string F(this string s, params object[] args)
{
return string.Format(s, args);
}

// like this one "lala {1} ".F(one, two)

//#C nice comparison tool :
public static bool Between<T>(this T actual, T lower, T upper) where T : IComparable<T>
{
return actual.CompareTo(lower) >= 0 && actual.CompareTo(upper) < 0;
}

//Allows to have :
if (myNumber.Between(3,7))
{
// ....
}

//#D a map function
public static void ForEach<T>(this IEnumerable<T> @enum, Action<T> mapFunction)
{
foreach (var item in @enum) mapFunction(item);
}

//allows to run function for every element
// like this one :
new { itemA, itemB, itemC }
.ForEach(item => {
item.Number = 1;
item.Str = "Hello World!";
});


Sunday

moving data between two list boxes +jquery

   

<select id="SelectLeft" multiple="multiple">
<option value="1">Australia</option>
<option value="2">New Zealand</option>
<option value="3">Canada</option>
<option value="4">USA</option>
<option value="5">France</option>
</select>

<input id="MoveRight" type="button" value=" >> " />
<input id="MoveLeft" type="button" value=" << " />

<select id="SelectRight" multiple="multiple">
</select>




<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
<script language="javascript" type="text/javascript">
$(function() {
$("#MoveRight,#MoveLeft").click(function(event) {
var id = $(event.target).attr("id");
var selectFrom = id == "MoveRight" ? "#SelectLeft" : "#SelectRight";
var moveTo = id == "MoveRight" ? "#SelectRight" : "#SelectLeft";

var selectedItems = $(selectFrom + " :selected").toArray();
$(moveTo).append(selectedItems);
selectedItems.remove;
});
});
</script>


Thursday

cross platform mobile development comparison

There's a detailed comparison of all these toolkits in this article here: Modern Cross Platform Development.
There are a number of other solutions around like
Rhodes,
Titanium,
PhoneGap,
JUCE,
MoSync,
Corona and
Moai.
Each of these use a bunch different languages, including HTML5/JS/CSS, Lua, Ruby, Python and C++. All except Corona are open source and free.

Tuesday

template method design pattern c#

      
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RulesDemo
{

/* messages */

public class MessageBase
{
public bool ClientActive { get; set; }
}


public class SPQMessage: MessageBase {
public bool Card {get;set;}
}

public class ACPMessage: MessageBase {
public bool URL {get;set;}
}


/* Ruule interface*/

public interface IRule {
string Evaluate (MessageBase messageBase);
string Evaluate (SPQMessage messageBase);
string Evaluate (ACPMessage messageBase);
}


/* rules */

/* rule base */
public class RuleBase: IRule {
public virtual string Evaluate(MessageBase messageBase)
{
throw new NotImplementedException();
}

public virtual string Evaluate(SPQMessage messageBase)
{
return Evaluate((MessageBase)messageBase);
}

public virtual string Evaluate(ACPMessage messageBase)
{
return Evaluate((MessageBase)messageBase);
}
}


/* concrete rules */
public class ClientIsActive : RuleBase
{
public override string Evaluate(MessageBase messageBase)
{
return "ClientIsActive";
}
}

public class UrlIsPresent : RuleBase
{
public override string Evaluate(ACPMessage messageBase)
{
return "UrlIsPresent";
}

}

/* */

class Program
{
static void Main(string[] args)
{

ArrayList list = new ArrayList();
list.Add(new ClientIsActive());
list.Add(new UrlIsPresent());


ACPMessage message = new ACPMessage();
foreach (IRule rule in list)
{
Console.WriteLine(rule.Evaluate(message));
}

/* this will crash because ACP rule doesn't know how to process SPQ message*/
/*
SPQMessage message2 = new SPQMessage();
foreach (IRule rule in list)
{
Console.WriteLine(rule.Evaluate(message2));
}
*/
Console.ReadLine();

}
}
}

msmq set permissions c#

 
private void CreateQueue(string qname)
{
try
{
if (!MessageQueue.Exists(qname))
{
MessageQueue.Create(qname);
MessageQueue messageQueue = new MessageQueue(qname);
//messageQueue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl);
messageQueue.SetPermissions("Local Service", MessageQueueAccessRights.FullControl);

}
}
catch (Exception e)
{

Debug.Write("Failed to setup queue:" + qname + ":" + e.ToString());
}

}


windows service installer class with event source creation

      
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
namespace ProcessingService
{
[RunInstaller(true)]
public partial class MyProcessorInstaller : System.Configuration.Install.Installer
{
private readonly ServiceProcessInstaller _processInstaller;
private readonly ServiceInstaller _svcInstaller;
public MyProcessorInstaller()
{
InitializeComponent();
_processInstaller = new ServiceProcessInstaller();
_svcInstaller = new ServiceInstaller();

_processInstaller.Account = ServiceAccount.LocalService;

_svcInstaller.StartType = ServiceStartMode.Automatic;
_svcInstaller.Description = "Describe here what service is doing. ";
_svcInstaller.DisplayName = "Processing Service";
_svcInstaller.ServiceName = "ProcessingService";



//Create Instance of EventLogInstaller
EventLogInstaller myEventLogInstaller = new EventLogInstaller();

// Set the Source of Event Log, to be created.
myEventLogInstaller.Source = "ProcessingService";

// Set the Log that source is created in
myEventLogInstaller.Log = "Application";

// Add myEventLogInstaller to the Installers Collection.
Installers.Add(myEventLogInstaller);


Installers.Add(_svcInstaller);
Installers.Add(_processInstaller);

}
}
}


reset sa password sql 2008

How to recover SA password on Microsoft SQL Server 2008 R2

When you are using MS SQL Server in mixed mode, it is very important that you know your SA password.

There can be different reasons you lost the password

  • Person who installed the SQL Server knows the password but has left the building.
  • You did not write down the password in your password file
  • Password file is lost

Steps to recover the SA password

  • Start SQL Server Configuration Manager

  • Stop the SQL services

  • Edit the properties of the SQL Service

  • Change the startup parameters of the SQL service by adding a –m; in front of the existing parameters

  • Start the SQL services. These are now running in Single User Mode.
  • Start CMD on tthe SQL server
  • Start the SQLCMD command. Now you will see following screen

  • Now we create a new user. Enter following commands
    • CREATE LOGIN recovery WITH PASSWORD = ‘TopSecret 1′ (Remember SQL server has default strong password policy
    • Go
      • Now this user is created
  • Now we grant the user a SYSADMIN roles using the same SQLCMD window.
    • sp_addsrvrolemember ‘recovery’, ‘sysadmin’
    • go
  • Stop the SQL service again
  • Change the SQL service properties back to the default settings

  • Start the SQL service again and use the new created login (recovery in my example)
  • Go via the security panel to the properties and change the password of the SA account.

  • Now write down the new SA password.

Monday

get url c# and get url stream

       
public string Get(string url)
{
Debug.WriteLine(url);

HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.UserAgent = GetRndUserAgent();

//This time, our method is GET.
WebReq.Method = "GET";
//From here on, it's all the same as above.
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//Let's show some information about the response
_log(""+WebResp.StatusCode);
_log(WebResp.Server);

//Now, we read the response (the string), and output it.
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
return _Answer.ReadToEnd();
}


public StreamReader GetStream(string url)
{
Debug.WriteLine(url);

HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
WebReq.UserAgent = GetRndUserAgent();

WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//_log("" + WebResp.StatusCode);
//_log(WebResp.Server);

Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
return _Answer;

}


jsonarray example in c#


public List<TwtAuthor> Search(string kw, int page)
{
List<TwtAuthor> ret = new List<TwtAuthor>();

string url =
string.Format(
"http://search.twitter.com/search.json?q={0}&rpp=100&include_entities=true&result_type=mixed&page{1}",kw.Replace(" ","%20"),page);

JsonObject jsonArray = JsonArray.Load(wl.GetStream(url)).ToJsonObject();

for (int i = 0; i < jsonArray["results"].Count; i++)
{

//jsonArray["results"][0]["created_at"]
TwtAuthor author = new TwtAuthor()
{
name = jsonArray["results"][i]["from_user"].ToString().Replace("\"",""),
UserID = jsonArray["results"][i]["from_user_id"].ToString(),
KwmimText = jsonArray["results"][i]["text"].ToString(),
// KwmimDate = DateTime.Parse(jsonArray["results"][i]["created_at"].ToString()), // entry.Published,
RecordCreated = DateTime.Now
};
ret.Add(author);
}


return ret;

}


Thursday

style for asp.net Gridview

This is part of css files that contains style description:
 
.mGrid {
width: 100%;
background-color: #fff;
margin: 5px 0 10px 0;
border: solid 1px #525252;
border-collapse:collapse;
}
.mGrid td {
padding: 2px;
border: solid 1px #c1c1c1;
color: #717171;
}
.mGrid th {
padding: 4px 2px;
color: #fff;
background: #424242 url(grd_head.png) repeat-x top;
border-left: solid 1px #525252;
font-size: 0.9em;
}
.mGrid .alt { background: #fcfcfc url(grd_alt.png) repeat-x top; }
.mGrid .pgr { background: #424242 url(grd_pgr.png) repeat-x top; }
.mGrid .pgr table { margin: 5px 0; }
.mGrid .pgr td {
border-width: 0;
padding: 0 6px;
border-left: solid 1px #666;
font-weight: bold;
color: #fff;
line-height: 12px;
}
.mGrid .pgr a { color: #666; text-decoration: none; }
.mGrid .pgrD A:link {color:#0466c1;}
.mGrid .pgr A:visited {color:#0466c1;}
.mGrid .pgr A:hover {color:#0466c1;}
.mGrid .pgr A:active {color:#0466c1;}
.mGrid .pgr a:hover { color: #000; text-decoration: none; }


images must be placed within style file
grd_alt.png
grd_head.png
grd_pgr.png

In grid this style can by defined as follows:
 
<asp:GridView ID=gv runat=server BorderWidth="0" CellPadding=0 CellSpacing=0 Width="100%" CssClass="mGrid"
AllowPaging=false AllowSorting=false AutoGenerateColumns="False" SkinID=gvSkinMergePeople>
<Columns>
<asp:TemplateField HeaderText="dealer#" >
<ItemTemplate>
<a href='Edit.aspx?id=<%#Eval("Id") %>'> <%#Eval("dealer_") %></a>
</ItemTemplate>


</asp:TemplateField>
<asp:BoundField HeaderText="Client Name" DataField="dealer_name" />
<asp:BoundField HeaderText="Group" DataField="group" />
<asp:BoundField HeaderText="industry" DataField="industry" />
<asp:BoundField HeaderText="status" DataField="dealer_status" />
<asp:BoundField HeaderText="service begins" DataField="service_begins" DataFormatString="{0:mm/dd/yyyy}" />
<asp:BoundField HeaderText="CommissionType" DataField="RevenueSegmentValue" />
<asp:BoundField HeaderText="BudRank" DataField="BudRank" />
<asp:BoundField HeaderText="ForecastRank" DataField="ForecastRank" />
</Columns>
<EmptyDataTemplate>
<table cellpadding=0 cellspacing=0 border=0 width=100% height=100%>
<tr>
<td align=center height="40">
<asp:Label ID=lblEmptyMessage runat=server Text="No Records Found" CssClass="NewPlainText"></asp:Label>
</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>



Tuesday

cut mp3 files windows

1.download mp3splt from http://mp3splt.sourceforge.net/mp3splt_page/downloads.php
2.Run mp3splt.exe with parameters - like on this example

c:\tools\mp3splt\mp3splt.exe %1 01.40 47.00
pause

some appstore games statistic

Physics Gamebox – $102 589

Ragdoll Cannon (запускали в АппСторе отдельно) – $12 361

Roly-Poly Cannon (запускали отдельно) – $18 795

Cover Orange версия для MAC OS – $13 276

Cover Orange версия для iPad – $476 320

Cover Orange версия для iPhone – $739 986

IAP для iPhone версии – $310 393

IAP для iPad версии – $40 740

Sunday

asp.net password field cleared on postback

add this into "if (IsPostBack){" section on page_load
if (!(String.IsNullOrEmpty(txtPassword.Text.Trim())))
{
txtPassword.Attributes["value"]= txtPassword.Text;
}


self discipline tips

1 - Start small. If you have a little trouble with self discipline and want to work on it, the best thing you can do is to start small, which generally means picking something you think you can succeed at. For example, say you find yourself every New Year's Eve promising yourself to go to the gym every week. Then, March comes along and you find you've not gone for two months. Instead of yelling at yourself for being stupid and lazy why not try modifying your pledge to something you feel you could do. For example, you might promise yourself instead that you'll park farther from the store when you go, to make yourself walk a little more. This is something manageable. Let the gym go hang, at least for now.

2 - One thing at a time. Another thing you can do is to try picking just one thing. Quite often we find ourselves overwhelmed with life and all the things we think we are supposed to be doing, and in response promise ourselves that we'll straighten everything out right away and then find ourselves failing again at all of them. One way out of this is to pick just one thing to work on. Say it's paying bills on time. Forget killing yourself trying to get to places on time or whatever else it is that you worry about. Set up a date and time to pay those bills and don't let any of the other stuff get in the way. Getting those bills paid on time a few months in a row can make you feel more sure of yourself and able to tackle other things.

3 - Don't let other's sway you. One thing to be wary of when attempting to rein in your history of impulsive or less than well thought out behavior patterns is to look at who you keep company with. Quite often people allow others to sabotage their efforts. This is quite obviously not conducive to modifying our self disciplinary issues. To get better at self discipline, you need to either find a way to not listen to these people, or to get them out of your life.

4 - Watch out for weak moments. One of the trickiest parts of self discipline is handling weak moments. These are the killers. We feel fat, or insipid. We feel lost or empty. We find we miss the thing we've chosen to give up, or hate the thing we've started to do. We hate everything. This is when we give up. It's easy to be strong and carry on when we're at the top of our game. It's these low points where we have to find a way though. The best thing you can do when you feel yourself hitting a weak spot is to talk to someone who is not only on your side but can help to remind you of the good that will come out of your sticking to whatever it was you decided on. It's sort of like a sponsor for AA. Call them when you feel weak or are beginning to wonder if what you've chosen to do is so important after all. Call them when you see yourself making reasons for doing something else. Just call them. If you don't have someone you can call or talk to, get yourself up and out of the situation. If you've promised yourself you'd quite biting your nails, then get yourself up and outside. Water the lawn or dig a hole. Do some knitting. Just do something, especially if it means using your hands, because it's really hard to nibble your nails when your fingers are busy.

5 - Fitting it into your lifestyle. To improve your self discipline, you need to make whatever it is you've decided to do fit into your lifestyle. It's generally not enough to just stomp your foot and say this is how things are going to be from now on. To make things work, you have to change the circumstances of the situation. For example, if you've decided that from now on, when you tell your children no, you will not take it back later and let them do whatever that thing was. In addition to making that promise to yourself, you have to make some changes to the situation itself. In this example, it might be something as simple as asking the child for a written request. Doing so causes the child to have to think about their request and it allows you to see more clearly what is being asked and whether it is something that should be allowed or not.

6 - Don't talk about it. Quite often when we make up our minds to do something, one of the first things we do is go around telling everyone we know what we are going to do. Or not do, if that's the case. Try not to do this. It severs no useful purpose and in fact can undermine your resolve. We might think that by telling everyone we are actually asking for help, or at least support, when in fact what we are really doing is looking for approval, that may or may not come. If it doesn't we tend to start wondering if our decision was right in the first place, which can make your self discipline begin to crumble.

7 - Milestones. One of the things you can do along the way is to mark milestones. It might be days or weeks, or months or even years. Or it might be something less easy to write down, such as noting how you feel a change in the way you view certain things. A diary is a good way to keep track of things like this, especially if the thing you're trying to make yourself do or stop doing is rather subtle, like being less critical of your spouse. You might only notice the difference by reading your own words for past days. Keeping a diary also helps you to keep in mind the thing you're working on, which is critical to success.

8 - Charting success. In addition to marking milestones, you might also consider giving yourself a means of measuring your success or failures. Again, many things in life don't necessarily have a grading scale so it's important to watch your milestones and then to gauge whether you've been succeeding at your goals. If you're not doing as well as you'd like, consider things you might do to make it better. If things are going well, keep on as you've been, you're doing great.

9 - Don't let slips stop you. One of the biggest threats to self discipline is slipping and then falling headlong into defeat. This is common with dieting. We are doing great, then one day, in a weak moment we eat a whole bag of miniature brownies. And then, rather than scold ourselves gently and get back on the horse, we tell ourselves we're hopeless and figure we've lost the battle. But we haven't. We only lose the battle when we refuse to fight. It doesn't matter how many times you fail, if you keep fighting, you'll always be in the game.

10 - Rewarding yourself. As with most things in life, if you reward yourself well, you'll find your sub-conscience begin to act as an ally rather than as a force trying to subvert your efforts. Pick something you really like and if possible something you'll be able to enjoy for more than a moment. Things like a hot bubble bath or a chocolate desert are nice, but they are gone the moment we finish. Other things, like a nice purse or golf club serve as reminders every time we see them.

These ten tips to help improve your self discipline can be used by anyone who is trying to think of ways to help their own self discipline. If you are such a person, I wish you all the luck in the world.


Saturday

Best Google I-O 2012

Google I - O 2012 - Android Design for Success
Google I - O 2012 - Building Android Applications that Use Web APIs
Google I - O 2012 - Building Mobile App Engine Backends for Android, iOS and the Web
Google I - O 2012 - From Weekend Hack to Funded Startup - How to Build Your Team and Raise Money
Google I - O 2012 - Go Concurrency Patterns
Google I - O 2012 - Go in Production
Google I - O 2012 - Google Cloud Messaging for Android
Google I - O 2012 - Managing Google Compute Engine Virtual Machines Through Google App Engine
Google I - O 2012 - Meet the Go Team
Google I - O 2012 - Navigation in Android
Google I - O 2012 - New Low-Level Media APIs in Android
Google I - O 2012 - SQL vs NoSQL - Battle of the Backends
Google I - O 2012 - Whats Possible with the Google Drive SDK
Google I - O 2012 - Writing Efficient Drive Apps for Android
Google I - O 2012 - Building High Performance Mobile Web Applications
Google I - O 2012 - Making Good Apps Great More Advanced Topics for Expert Android Developers
Google I - O 2012 - Multi-Versioning Android User Interfaces
Google I - O 2012 - The Sensitive Side of Android
Google I - O 2012 - For Butter or Worse Smoothing Out Performance in Android UIs
Google I - O 2012 - Getting the Most Out of Python 2.7 on App Engine
Google I - O 2012 - Introducing Google Compute Engine
Google I - O 2012 - Security and Privacy in Android Apps


Tuesday

jquery mobile caching issue resolved

below is set of scripts I added to page header to resolve jquery mobile caching issue
       


<!DOCTYPE html>
<html>
<head runat="server">
<meta charset="utf-8">
<title>Personal Info</title>
<link href="mobile.css" rel="stylesheet" type="text/css"/>

<link href="jquery.mobile.theme-1.0.min.css" rel="stylesheet" type="text/css"/>
<link href="jquery.mobile.structure-1.0.min.css" rel="stylesheet" type="text/css"/>
<script src="jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="jquery.mobile-1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).bind("mobileinit", function () {
$.mobile.ajaxEnabled = false;
});

$("#form1").submit(function(){
$.mobile.changePage({
url: "PersonalInfo.aspx",
type: "post",
data: $("form#form1").serialize()
}, "pop", false, false);
}
return false;
});

</script>
</head> <body> <form id="form1" runat="server"> ...

Monday

asp.net jquery mobile grid


<asp:Panel ID="pnlResult" runat="server" >
<asp:Repeater ID="lstMMembership" runat="server">

<HeaderTemplate>
<div class="ui-grid-d">

<div class="ui-bar ui-bar-b">

<div class="ui-block-a"><%=loc("plHLastName")%></div>
<div class="ui-block-b"><%=loc("plHFirstName")%></div>
<div class="ui-block-c"><%=loc("plHDateOfBirth")%></div>
<div class="ui-block-d"> </div>
<div class="ui-block-e"> </div>

</div>

</HeaderTemplate>

<FooterTemplate>
</div>
</FooterTemplate>

<ItemTemplate>
<div class="ui-bar ui-bar-c">
<div class="ui-block-a"> <%#DataBinder.Eval(Container.DataItem, "LastName")%> </div>
<div class="ui-block-b"><%#DataBinder.Eval(Container.DataItem, "FirstName")%> </div>
<div class="ui-block-c"><%#DateToString(DataBinder.Eval(Container.DataItem, "DateOfBirth"))%> </div>
<div class="ui-block-d"> <a href='PersonalInfo.aspx?i=<%#DataBinder.Eval(Container.DataItem, "MembershipNumber")%>' data-role="button"><img src='pencil32.png' /></a></div>
<div class="ui-block-e"> <a href='PersonalInfo.aspx?i=<%#DataBinder.Eval(Container.DataItem, "MembershipNumber")%>' data-role="button"><img src='bargraph32.png' /></a></div>
</div>



</ItemTemplate>

</asp:Repeater>

toledo weights vb6 code


Public Shared STX = Chr(2)' ascii start of text
Public Shared CR = Chr(13) 'ascii Carriage Return

Private Function get_lbs() As String
Dim buffer As New StringBuilder()
Dim comPort As New SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)

comPort.Open()
comPort.Write(STX)
mytimer(1)
comPort.Write("P")
mytimer(1)
comPort.Write(CR)
mytimer(1)
Dim line As String = comPort.ReadExisting
comPort.Close()
Return isnum(Trim(line))

End Function

Tuesday

jquery checkbox check all


<script type="text/javascript">
$(document).ready(function()
{

$('#chkAll').click(
function()
{
$("INPUT[type='checkbox']").attr('checked', $('#chkAll').is(':checked'));
}
)

}
);
</script>

<asp:TemplateColumn HeaderText="" headerstyle-cssclass="NormalBold">
<HeaderTemplate>
<input type='checkbox' id='chkAll' >
</HeaderTemplate>

<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateColumn>


SQL Server 2000 DTS Designer components are required to edit DTS packages.


I've got this error when opening DTS package in Microsoft SQL Server Management Studio:
SQL Server 2000 DTS Designer components are required to edit DTS packages. Install the special Web download, "SQL Server 2000 DTS Designer Components" to use this feature. (Microsoft.SqlServer.DtsObjectExplorerUI)

Problem was fixed after changing order in Path variables (System Properties/Environment Variables/System variables):

C:\Program Files\Microsoft SQL Server\80\Tools\Binn\; should appear before the
C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;


Incase of 64 bit machine:
C:\Program Files (x86)\Microsoft SQL Server\80\Tools\Binn\;

Please make sure to restart Microsoft SQL Server Management Studio after changing path.

Thursday

xdocument elements getting by SafeElement function


public string SafeElem(XDocument x, string tag, string _default_)
{
string r = _default_;
IEnumerable<XElement> a = x.Elements(tag);
if (a!=null && a.Count() >0)
{
string g= a.First().Value;
if (!string.IsNullOrEmpty(g))
{
r = g;
}
}
return r;
}


Friday

free online courses

Широко известный проект Coursera объявил о заключении партнерской программы со следующими университетами:

Курсы охватывают широкий круг вопросов, в том числе компьютерные науки, гуманитарные науки, медицину, биологию, социальные науки, математику, статистику, экономику, финансы, а также многие другие темы. В общей сложности доступно около 40 курсов, 6 из которых планируется начать в следующий понедельник, 23 апреля:

Классы, предлагаемые на Coursera, разработаны для того, чтобы помочь вам освоить материал. Вы сможете смотреть лекции профессоров мирового класса, учиться в своем собственном темпе, проверить и укрепить свои знания с помощью интерактивных упражнений. Регистрируясь в Coursera, вы также присоединяетесь к мировому сообществу тысяч студентов, занимающихся вместе с вами.

Thursday

javascript parse number from string

use parseFloat and parseInt functions like on samples below:

1 parseFloat('1.45kg') // 1.45
2 parseFloat('77.3') // 77.3
3 parseInt('123.45') // 123
4 parseInt('77') // 77
5

vim msbuild

1. create build.bat file for building your project

call "c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86
msbuild c:\myproject\Source\myProject.sln


2.Run following commands in VIM or add to .vimrc
:set makeprg=c:\myproject\Source\build.bat
:set errorformat=\ %#%f(%l\\\,%c):\ %m

3.execute following command to build your project
:make

4.Open output window by
:cope

Tuesday

combobox selectedvalue problem net

When I'm adding new items to combobox like in this post.
There was problem in reading this value on dserver side.
So here is solution how to do this.

string selectedValue = Request.Params[combobox.UniqueId]

Monday

jquery clear dropdown values

use this command to clear dropdown items:

$('#mySelect').empty()

asp.net jquery ajax data webmethod post


1.Code - behind class
  
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Modules.MembershipModule;

namespace VoluntaryShop
{
public partial class jsonhub : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string Test()
{
return "OK";
}

[WebMethod]
public static ArrayList MSearchVolunteersbyGroup(int Group)
{
Debug.Write("MSearchVolunteersbyGroup"+Group);
MembershipModuleController c = new MembershipModuleController();
return c.MSearchVolunteersbyGroup(Group);
}
}
}


2.ASPX Page:
   
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="jsonhub.aspx.cs" Inherits="VoluntaryShop.jsonhub" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"> </script>
<script type="text/javascript">
function PageMethod(fn, paramArray, successFn, errorFn) {
var pagePath = window.location.pathname;
//Create list of parameters in the form:
//{"paramName1":"paramValue1","paramName2":"paramValue2"}
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
//Call the page method
$.ajax({
type: "POST",
url: pagePath + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: successFn,
error: errorFn
})
;
}
</script>

<script type="text/javascript">


function AjaxSucceeded(result) {
alert(result.d);
alert(result.d[0].FirstName);

}
function AjaxFailed(result) {

alert("failed"+result.d);
}

PageMethod("MSearchVolunteersbyGroup", ["Group","1"], AjaxSucceeded, AjaxFailed); //No parameters
</script>


</head>
<body>
<form id="form1" runat="server">
<div>

</div>
</form>
</body>
</html>

imagemagic add text to image

rem different types of text annotations on existing images rem cyan yellow orange gold rem -gravity SouthWest rem draw text and anno...