Declare @products varchar(200) = 'one::two::tree'
Declare @individual varchar(20) = null
declare @res table(ident int identity(1,1),val varchar(20))
WHILE LEN(@products) > 0
BEGIN
IF PATINDEX('%::%',@products) > 0
BEGIN
SET @individual = SUBSTRING(@products, 0, PATINDEX('%::%',@products))
Insert into @res (val) values (@individual)
SET @products = SUBSTRING(@products, LEN(@individual + ';;') + 1,
LEN(@products))
END
ELSE
BEGIN
SET @individual = @products
SET @products = NULL
Insert into @res (val) values (@individual)
END
END
Select * from @res p
Pivot( max(p.val) for p.ident in ([1],[2],[3]) ) as PIV
Tuesday
ms sql split string into columns
here is excellent example how to split string into columns in TSQL (microsoft SQL server)
.bat random number generator
here is example how to use random in bat files in simple 'guess number' game.
to call it : game.bat [total numbers to pick from] [your number]
for example : game.bat 6 3
to call it : game.bat [total numbers to pick from] [your number]
for example : game.bat 6 3
set /a NUM = ( %1 * %random% ) / 32768 + 1
IF "%NUM%" EQU "%2" (echo "winner!") else (echo "loose %NUM%")
create documentation from biztalk binding file
I create simple xslt for getting information about each orchestrations and ports from binding file.
Result html could be created by :
<xml tr c:\temp\my.xsl MyBindingInfo.xml > c:\temp\mydoc.html
Result html could be created by :
<xml tr c:\temp\my.xsl MyBindingInfo.xml > c:\temp\mydoc.html
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="text()" />
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="Service">
<p>
<h3>service:<b><xsl:value-of select="@Name"/></b></h3>
ports:<br/>
<xsl:apply-templates select="Ports/Port"/>
</p>
</xsl:template>
<xsl:template match="Ports/Port">
Logical Port: <b><xsl:value-of select="@Name"/></b>
Physical
<xsl:apply-templates select="SendPortRef"/>
<xsl:apply-templates select="ReceivePortRef"/>
</xsl:template>
<xsl:template match="SendPortRef">
<xsl:if test="@Name != ''">
Send Port:<b><xsl:value-of select="@Name"/></b><br />
</xsl:if>
</xsl:template>
<xsl:template match="ReceivePortRef">
<xsl:if test="@Name != ''">
Receive Port:<b><xsl:value-of select="@Name"/></b><br/>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Monday
sql add zeros in front of number
Right function can be use to perform this formatting.For example - if we have table with
column containing numbers and we have to add leading zeros to these number we can do following:
column containing numbers and we have to add leading zeros to these number we can do following:
SELECT * FROM Numbers;
Num
12
112
12
122
122
5 row(s) affected.
Formatting:
SELECT RIGHT('00000'+ CONVERT(VARCHAR,Num),6) AS NUM FROM Numbers;
NUM
000012
000112
000012
000122
000122
5 row(s) affected.
text templates c#
This is simple implementation of search/replace template engine in c#
Template class is following:
Sample template file will be looking like this:
And code for calling this awesome template engine will be following:
Template class is following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Xml.Linq;
using System.Linq;
public class Templates
{
private Hashtable templates;
public Templates(string templatesFilePath)
{
templates = new Hashtable();
System.IO.StreamReader confFile = new System.IO.StreamReader(templatesFilePath);
XDocument configuration =XDocument.Parse(confFile.ReadToEnd());
var tpls = from cs in configuration.Descendants("Template")
select cs;
foreach (var t in tpls)
{
templates.Add(t.Attribute("Name").Value,t.Value);
}
}
/// <summary>
/// REnder templates with
/// </summary>
/// <param name="templateName"></param>
/// <param name="values"></param>
/// <returns></returns>
public string Render(string templateName, params string[] values)
{
Hashtable hash = new Hashtable();
for (int i = 0; i <= Math.Floor((decimal)values.Length/2); i+=2)
{
hash.Add(values[i], values[i + 1]);
}
return Render(templateName, hash);
}
/// <summary>
/// Renders
/// </summary>
/// <param name="templateName"></param>
/// <param name="values"></param>
/// <returns></returns>
public string Render(string templateName,Hashtable values)
{
string result = String.Empty;
if (templates.ContainsKey(templateName))
{
string template = (string)templates[templateName];
foreach (DictionaryEntry entry in values)
{
template = template.Replace("{$" + entry.Key + "}", "" + entry.Value);
}
result = template;
} else {
}
return result;
}
}
Sample template file will be looking like this:
<Templates>
<Template Name="template1">
<![CDATA[
My first template with {$Value1}
and {$Value2}
]]>
</Template>
<Template Name="template2">
<![CDATA[
My second template with {$Value3} and {$Value4}
]]>
</Template>
</Templates>
And code for calling this awesome template engine will be following:
Templates templates = new Templates(ConfigManager.AssemblyDirectory + @"\MyTemplates.xml");
var result=templates.Render("template1", "Value1", Aome Value1, "Value2", DateTime.Now.ToString("yyyy-MM-ddThh:mm:ss")));
Tuesday
get current folder c#
here is how to get current folder for assembly in c#
using System.Reflection;
static public string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
Wednesday
temporary file stream c#
public class TempFileStream : FileStream
{
public TempFileStream()
: base(Path.GetTempFileName(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose) { }
public TempFileStream(FileAccess access)
: base(Path.GetTempFileName(), FileMode.Create, access, FileShare.Read, 4096, FileOptions.DeleteOnClose) { }
public TempFileStream(FileAccess access, FileShare share)
: base(Path.GetTempFileName(), FileMode.Create, access, share, 4096, FileOptions.DeleteOnClose) { }
public TempFileStream(FileAccess access, FileShare share, int bufferSize)
: base(Path.GetTempFileName(), FileMode.Create, access, share, bufferSize, FileOptions.DeleteOnClose) { }
}
Friday
Главное, что я понял
Главное, что я понял — это то, что в человеке заложено огромное количество сил и энергии. Если мы несем ответственность за свою жизнь, то мы эти силы направляем на вполне позитивные, правильные вещи — бизнес, карьера, построение качественной личной жизни. Если же мы предпочитаем пассивное времяпровождение — то нам остается интернет, ТВ, пиво и прочие прелести потребительского образа недожизни. Каждому — свое.
Но силы есть у всех.
Thursday
how to create the perfect blog post
Perfect blog post must include following elements (from 1 to 13):
1.Big catchy header in 30px font size
2.First copy of social links and comments (there are should be two sets one in the beginning of the article and another at the end)
3.Short introduction into problem in big letters 20px
with question but without giving actual response but giving answers on the main questions.
For example :
Almost every time I speak on the topic of [MainTopic], someone asks,
How often do I need to do [MainAction] to build [MainTopic]?
The truth is, my opinion has changed over the years.
4.Short Video - this element is good to hold user on the page for some time
Should be no longer then 3 minutes.
5.Main Text 3 paragraphs 16 pixels font size.
6.Paragraph with link on popular site gizmodo for ex. with title like on the site and target blank
7.Last conclusive paragraph with asking to watch the video and comment
Before you watch the video, take a guess at what you think it is and leave a comment below.
Then watch the video (it's less than three minutes long) and come back and tell me if you were right.
8.Last question 24 px italic what do you think leave comment , etc....
for example:
Question: What do you think could be more important than blogging frequency for building a platform? You can leave a comment by clicking here.
9.Final actions island , gray background island with all link you want user to go
10.Second set of social links
11.If you are posting affiliate links , add disclosure in small letters .
12.Links on [previous] and [next] post.
13.Actual comments
Check out my next post about how to turn work into game.
1.Big catchy header in 30px font size
2.First copy of social links and comments (there are should be two sets one in the beginning of the article and another at the end)
3.Short introduction into problem in big letters 20px
with question but without giving actual response but giving answers on the main questions.
For example :
Almost every time I speak on the topic of [MainTopic], someone asks,
How often do I need to do [MainAction] to build [MainTopic]?
The truth is, my opinion has changed over the years.
4.Short Video - this element is good to hold user on the page for some time
Should be no longer then 3 minutes.
5.Main Text 3 paragraphs 16 pixels font size.
6.Paragraph with link on popular site gizmodo for ex. with title like on the site and target blank
7.Last conclusive paragraph with asking to watch the video and comment
Before you watch the video, take a guess at what you think it is and leave a comment below.
Then watch the video (it's less than three minutes long) and come back and tell me if you were right.
8.Last question 24 px italic what do you think leave comment , etc....
for example:
Question: What do you think could be more important than blogging frequency for building a platform? You can leave a comment by clicking here.
9.Final actions island , gray background island with all link you want user to go
<div style="background-color:#eaeaea; border:1px solid #D5D5D5; font-family:arial,helvetica,sans-serif; font-size:15px; line-height:20px; margin-bottom:20px; margin-top:8px; padding:15px 20px;">
Search on Google, it's fun <a target="_blank" title="Use google" href="http://www.google.com">google</a>.
Also, buy things on amazon <a target="_blank" title="buy at amazon" href="buy at amazon.com">Amazon</a>.
Nike I personally recommend. <a target="_blank" title="Nike" href="www.nike.com">Nike...</a>.
</div>
10.Second set of social links
11.If you are posting affiliate links , add disclosure in small letters .
Disclosure of Material Connection: Some of the links in the post above are "affiliate links." This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, I only recommend products or services I use personally and believe will add value to my readers. I am disclosing this in accordance with the Federal Trade Commission's <a href="http://www.access.gpo.gov/nara/cfr/waisidx_03/16cfr255_03.html" target="_blank">16 CFR, Part 255</a>: "Guides Concerning the Use of Endorsements and Testimonials in Advertising".
12.Links on [previous] and [next] post.
13.Actual comments
Check out my next post about how to turn work into game.
Wednesday
biztalk schema reference is not a valid reference or does not exist in the current project
This error may occur when WCF service added to Biztalk by "Add service reference" but this service should be added by using the Add Generated Items wizard.
This wizard capable to import all xsd files into Biztalk project and create correct schemes.
This wizard capable to import all xsd files into Biztalk project and create correct schemes.
Tuesday
how to find assembly in gac
to find if assembly installed in GAC run visual studio command line and in opened window type following
This will return all assemblies that has MyAssembly in name.
Also here is link on gacutil command line options
C:\Windows\system32>gacutil -l | find "MyAssembly"
This will return all assemblies that has MyAssembly in name.
Also here is link on gacutil command line options
microsoft.biztalk.interop.ssoclient error
I was trying to configure biztalk 2013 sftp adapter and was getting this error in EventLog
Reason: "System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.BizTalk.Interop.SSOClient, Version=7.0.2300.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
It turns out that there is no BizTalk Interop SSOClient in the GAC
I resolved this problem by finding ESSO on Biztalk DVD and manually upgrade SSO and this resolved the problem :
Reason: "System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.BizTalk.Interop.SSOClient, Version=7.0.2300.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.
It turns out that there is no BizTalk Interop SSOClient in the GAC
C:\Windows\system32>gacutil -l | find "Microsoft.BizTalk.Interop.SSOClient" Microsoft.BizTalk.Interop.SSOClient, Version=5.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL Microsoft.BizTalk.Interop.SSOClient, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
I resolved this problem by finding ESSO on Biztalk DVD and manually upgrade SSO and this resolved the problem :
C:\Windows\system32>gacutil -l | find "Microsoft.BizTalk.Interop.SSOClient" Microsoft.BizTalk.Interop.SSOClient, Version=7.0.2300.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL
select count from all tables in database
To get count of records in all database please use following query:
--DROP table #counts
CREATE TABLE #counts
(
table_name varchar(255),
row_count int
)
EXEC sp_MSForEachTable @command1='INSERT #counts (table_name, row_count) SELECT ''?'', COUNT(*) FROM ?'
SELECT table_name, row_count FROM #counts ORDER BY table_name, row_count DESC
Friday
t-sql unit testing
Here is simple t-sql unit testing approach by writing sql script that will do all testing work.
I like this solution the most because it's very flexible and doesn't require additional installations on sql server.
Also I think the best way to write sql unit tests is to make them independent from data.And validate logic but not data.
Such unit tests can be run on development or qa and even production environment.
Also there are another sql unit test frameworks .
I like this solution the most because it's very flexible and doesn't require additional installations on sql server.
Also I think the best way to write sql unit tests is to make them independent from data.And validate logic but not data.
Such unit tests can be run on development or qa and even production environment.
--Unit Test example
--SETUP
declare @ActualData varchar(10) , @ExpectedResult varchar(10)
-- RUN
SET @ActualData ='a'
Set @ExpectedResult ='b'
-- VALIDATE
IF @ActualData!= @ExpectedResult
RAISERROR('>> Unit Test FAILED: Returned data doen''t match expected: %s instead of %s ', 11, 0, @ActualData ,@ExpectedResult )
Also there are another sql unit test frameworks .
Tuesday
jquery textbox change event not firing
Try to use live event instead of change or onchange as follows:
$('#myTextBoxId').live('input', function () {
MyFunction();
});
Monday
jquery select add remove item
to add new option to select control with DropDownId id :
$('#DropDownId').append(new Option('text','val'));
to remove option to select control with DropDownId id:
$("#DropDownId option[value='val1']").remove();
$("#DropDownId option:contains('val1')").remove();
mvc model not updating
To resolve this issue try to add this instruction before calling view and see if it works ModelState.Clear();
public ViewResult SomeAction(SomeModel model)
{
var newModel = new SomeModel { SomeString = "some value" };
ModelState.Clear();
return View(model);
}
Friday
jquery ajax post form values
<script type="text/javascript">
$(document).ready(function () {
$("#SaveReportButton").click(function (event) {
event.preventDefault();
var $form = $(this).parents('form');
$.ajax({
type: "POST",
url: '@Url.Action("SaveDistributionReport")',
data: $form.serialize(),
error: function(xhr, status, error) {
//do something about the error
},
success: function(response) {
//save selected value
}
});
});
});
</script>
vim show tabstops
" highlight tabs and trailing spaces
set listchars=tab:>-,trail:-
set list
set tabstop=4
Monday
html.radiobuttonfor onclick for tracking change event
here is example how to use onclick event for tracking changes in radio button group.
so when radio button control will be changed , onPropertyChanged javascript function will be called passing value of radio button as argument.
@Html.LabelFor(m => m.BoolProperty)
@Html.RadioButtonFor(m => m.BoolProperty, true, new { onclick= "onPropertyChanged(true);" })
@StringResources.Submitted
@Html.RadioButtonFor(m => m.BoolProperty, false, new { onclick = "onPropertyChanged(false);" })
@StringResources.Fulfillment
so when radio button control will be changed , onPropertyChanged javascript function will be called passing value of radio button as argument.
Sunday
кожа для вордпресс, которую купили 27 тыс раз на сумму 1.5 мегабакса
кожа для вордпресс, которую купили 27 тыс раз на сумму 1.5 мегабакса
Вот тема для вордпресса, стоит $55. Ее продали 27+ тыс раз, на сумму 1.485 килобаксов (чуть менее 1.5 мегабакса). Самая продаваемая тема для вордпресса. Начало продаж 4 июня 2011.
Шароварщики нервно курят в сторонке (уж по соотношению доход/"затраты на разработку").
ЗЫ: попал на ту страничку увидев adwords на сайте sdelanounas.ru, сидя в инете с немецкого IP адреса. То есть магазин themeforest дает рекламу своих самых продаваемых продуктов.
Вот тема для вордпресса, стоит $55. Ее продали 27+ тыс раз, на сумму 1.485 килобаксов (чуть менее 1.5 мегабакса). Самая продаваемая тема для вордпресса. Начало продаж 4 июня 2011.
Шароварщики нервно курят в сторонке (уж по соотношению доход/"затраты на разработку").
ЗЫ: попал на ту страничку увидев adwords на сайте sdelanounas.ru, сидя в инете с немецкого IP адреса. То есть магазин themeforest дает рекламу своих самых продаваемых продуктов.
Friday
developer productivity metrics
- Productivity
- Does the developer get a reasonable amount of work done in a given period of time?
- Is the developer's velocity on bug fixing sufficient?
- Engagement
- Is the developer dedicated to his/her craft?
- Is the developer committed to delivering software on time?
- Is the developer dedicated to company success?
- Attention to Quality
- To what degree does the developer's code work as designed?
- Does the developer thoroughly test code and believe it to be correct before checking it in?
- Do a minimal number of bugs get reported against his/her code?
- Does the developer write unit tests for all new code?
- Does the developer follow the Boy Scout Rule and leave a module cleaner than it was before he or she worked on it?
- Code Base Knowledge and Management
- To what degree does the developer understand the code base assigned to him/her?
- Does the developer take responsibility for his/her team's code base, improving it at every opportunity?
- Adherence to coding guidelines and techniques
- Does developer's code routinely meet coding standards?
- Do code reviews reveal a minimum of problems and discrepancies?
- Does the developer use Dependency Injection to ensure decoupled code?
- Learning and Skills
- Is the developer constantly learning and improving his/her skills?
- Does the developer show a passion for the craft of software development?
- Personal Responsibility
- Does the developer first assume that the error lies within his or her code?
- Does the developer understand that he or she is solely responsible for their code working correctly?
- Does the developer take pride in their code, ensuring it is clean, tested, easy to read, and easy to maintain?
c# datetime beginning of day
This extension adds EndOfDay StartOfDay methods to DateTime so it's possible to call
DateFrom.Value.StartOfDay() or dateTo.Value.EndOfDay()
DateFrom.Value.StartOfDay() or dateTo.Value.EndOfDay()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AwesomeExtensions
{
public static class Extension
{
public static DateTime EndOfDay(this DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 23, 59, 59, 999);
}
public static DateTime StartOfDay(this DateTime date)
{
return new DateTime(date.Year, date.Month, date.Day, 0, 0, 0, 0);
}
}
}
selenium popup example in c#
// waiting for popup to open
while (this.driver.WindowHandles.Count == 1)
{
this.WaitASec();
}
this.WaitASec();
// save the current window handle.
String parentWindowHandle = driver.CurrentWindowHandle;
IWebDriver popup = null;
var windowIterator = driver.WindowHandles;
bool onefound = false;
//enumerate through all windows to make sure at least one contains required text
foreach (var windowHandle in windowIterator)
{
popup = driver.SwitchTo().Window(windowHandle);
if (textPresent != "")
{
onefound=Regex.IsMatch(popup.FindElement(By.CssSelector("BODY")).Text, "^[\\s\\S]*" + textPresent + "[\\s\\S]*$");
}
}
Assert.IsTrue(onefound,"No text was found "+textPresent);
Wednesday
accessed from a thread other than the thread it was created on.
This happends when you are trying to modify control from another thread.You cannot do this directly it could be done only by invoker.
In order to resolve this situation please do following:
step 1: Create following extension
step2.Using developed extension:
Now in other thread instead of calling control directly like :
You have to call it as follows:
In order to resolve this situation please do following:
step 1: Create following extension
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
public static class Extension
{
public static void InvokeIfRequired(this Control control, MethodInvoker action)
{
if (control.InvokeRequired)
{
control.Invoke(action);
}
else
{
action();
}
}
}
step2.Using developed extension:
Now in other thread instead of calling control directly like :
htmlPanel1.Text = resml;
You have to call it as follows:
htmlPanel1.InvokeIfRequired(() =>{ htmlPanel1.Text = resml; });
Tuesday
@html.dropdownlistfor onchange
here is how to add javascript onchange function to DropDownListFor MVC helper:
@Html.DropDownListFor(m => m.SettingValue, new SelectList(Model.globalTypes, "TypeCode", "TypeName"), new { onchange = "SettingChanged()" })
Friday
jquery save and restore form data
Here is sample how to store and retrieve form and retrieve data
Here is the function
// get all form values into json
var s2=$('form').values();
// restore all forms values back
$('form').values(s2);
Here is the function
/* function for form saving restoring code */
$.fn.values = function (data) {
var els = $(this).find(':input').get();
if (typeof data != 'object') {
// return all data
data = {};
$.each(els, function () {
if (this.name && !this.disabled && this.type != "hidden") {
if (this.type == 'checkbox') {
data[this.name] = $(this).is(":checked");
} else if (this.type == 'radio') {
if ($(this).is(":checked")) {
data[this.name] = $(this).val();
}
} else {
data[this.name] = $(this).val();
}
}
});
return data;
} else {
$.each(els, function () {
if (this.name && data[this.name] != null) {
//console.log(">" + this.name + " " + data[this.name]);
if (this.type == 'checkbox') {
$(this).attr("checked", data[this.name]); //(data[this.name] == $(this).val())
//console.log("checkbox");
} else if (this.type == 'radio') {
$(this).attr("checked", data[this.name] == $(this).val());
} else {
$(this).val(data[this.name]);
}
}
});
return $(this);
}
};
Product Opportunity Assessment
1. Exactly what problem will this solve? (value proposition)
2. For whom do we solve that problem? (target market)
3. How big is the opportunity? (market size)
4. What alternatives are out there? (competitive landscape)
5. Why are we best suited to pursue this? (our differentiator)
6. Why now? (market window)
7. How will we get this product to market? (go-to-market strategy)
8. How will we measure success/make money from this product? (metrics/revenue strategy)
9. What factors are critical to success? (solution requirements)
10. Given the above, what’s the recommendation? (go or no-go)
2. For whom do we solve that problem? (target market)
3. How big is the opportunity? (market size)
4. What alternatives are out there? (competitive landscape)
5. Why are we best suited to pursue this? (our differentiator)
6. Why now? (market window)
7. How will we get this product to market? (go-to-market strategy)
8. How will we measure success/make money from this product? (metrics/revenue strategy)
9. What factors are critical to success? (solution requirements)
10. Given the above, what’s the recommendation? (go or no-go)
Wednesday
javascript delete confirmation dialog box
function DeleteSpecificClient(gridId, gridModel) {
var ac2del = 0;
var allVals = 'dels='; $('#' + gridId).find('.idCheckbox:checked').each(function () {
allVals += $(this).attr("id") + ","; ac2del += 1;
});
if (ac2del == 0) return; // exit if no group selected
var dia = $('#deleteClientsPopup').html(ac2del + " @StringResources.DeletingDialogMessage" + ".<br>");
var xhr;
dia.dialogInit({
title:"@StringResources.DeleteDialogTitle",
modal: true,
resizable: false,
autoResize: true,
autopen:true,
buttons: [
{
id: "SaveButton",
text: "Delete",
click: function (event) {
var grid = $find(gridModel.gridId());
grid.ShowWaitingPopup();
dia.dialog("close");
xhr= $.ajax({
type: 'POST',
url: '@Url.ApplicationAction("DeleteClientsFromList", "LoggingSettings")',
data: allVals,
cache: false,
success: function (data) {
ReloadSelectedClientsGrid();
DisableDelButton();
},
error: function (xhr, data, message) {
//console.log(data + ": " + message);
},
dataType: "json"
});
}
},
{
id: "CancelButton",
text: "Cancel",
click: function () {
try {
xhr.abort();
} catch (err) {
}
dia.dialog("close");
}
}
]
});
dia.dialog("open");
return false;
};
css cellpadding cellspacing border table
following css settings are equivalent to cellpadding='0' cellspacing='0'
.ReportFormsFieldSet{
border:0;
border-spacing:0;
border-collapse:collapse;
}
jquery drag over element
<html><head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" ></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script language='javascript'>
$(document).ready(function () {
$(".cell").draggable({
over : function(event, ui) {
alert('');
},
helper: 'clone'
});
$('.cell').droppable({
over : function(event, ui) {
alert( $(this).attr("id"));
}
});
});
</script>
</head>
<body>
<table border='1'><tr>
<td class='cell' id='base' >
[ one ]
</td>
<td class='cell' id='detail'>
[ test ]
</td>
</tr></table>
</body>
jquery get first link in div
this expression returns text of first link in div
$('#dvPaymentStatus a:first').text()
jquery all except one
here is jquery how to get all elements except one:
$('#dvPaymentStatus').find("input[type=checkbox]:checked").not('#PaymentStatus_SelectAll').size()
Monday
mvc get html from view
add method below to controller then you will be able to get html from any view by:
this.RenderView("myView");
this.RenderView("myView");
/// <summary>
/// get html from view
/// </summary>
public string RenderView(string ViewName)
{
var content = string.Empty;
var view = ViewEngines.Engines.FindView(ControllerContext, ViewName, null);
using (var writer = new StringWriter())
{
var context = new ViewContext(ControllerContext, view.View, ViewData, TempData, writer);
view.View.Render(context, writer);
writer.Flush();
content = writer.ToString();
}
return content;
}
Wednesday
asp.net mvc ajax post model
If model contain variable of class Class1 with properties Property1,Property2.
Submitted parameters must be named:
"Class1.Property1"
"Class1.Property2"
If model has property as List<Record> submitted values must be :
"Class1[0].Property1"
"Class1[0].Property2"
"Class1[1].Property1"
"Class1[1].Property2"
"Class1[2].Property1"
"Class1[2].Property2"
Here are samples of two functions that creates this values dynamically before submitting form.
Submitted parameters must be named:
"Class1.Property1"
"Class1.Property2"
If model has property as List<Record> submitted values must be :
"Class1[0].Property1"
"Class1[0].Property2"
"Class1[1].Property1"
"Class1[1].Property2"
"Class1[2].Property1"
"Class1[2].Property2"
Here are samples of two functions that creates this values dynamically before submitting form.
//this function create parameters for sending them over AJAX
function ConvertJSONIntoPostableHTML() {
var params = {
param1 : 'myvalue',
};
if (Jsonrecord != null) {
for (var i = 0; i < Jsonrecord.length; i++) {
var rec = Jsonrecord[i];
$.each(Object.keys(rec), function(j, value) {
params["Records[" + i + "]." + value] = rec[value];
});
}
}
return params;
}
//this function add parameters to form , then form can be submitted
function SelectedNodes(frm) {
$(".tslct").remove();
var i = 0;
$.each(myJsonCollection, function () {
var obj = "Nodes[" + i + "].";
addElem(frm, obj + "Id", this.Id);
addElem(frm, obj + "Value", this.Type);
i++;
}
);
}
jquery add element to form dynamically
//function that adds element to form
function addElem(frm, id, val) {
$('<input>').attr({
type: 'hidden',
id: id,
name: id,
value: val,
class: 'tslct'
}).appendTo(frm);
}
//example of using of this function
var frm = $(this).closest('form');
addElem(frm, "myId", "myvalue");
Tuesday
use of hashtable in javascript
here is an example of usage of hashtable in javascript.For example I want to asociate specific buttonId
with specific grid Id I could create following hashtable:
Then I could use it in code :
with specific grid Id I could create following hashtable:
var GridsButtons = {
'AGroupsListGrid' :'DelA',
'BGroupsListGrid' :'DelB'
};
Then I could use it in code :
var buttonid = GridsButtons[gid];
asp.net mvc ajax post from javascript
Following example demonstrate how to submit form in asp.net MVC for strict type view based on model:
(view has this instruction oin top:
@model MyModel
):
javascript part:
on server side model variable will have updated with all values submitted in form and will have following parameters:
(view has this instruction oin top:
@model MyModel
):
javascript part:
<script type="text/javascript">
$(document).ready(function() {
$("#GoButton").click(function() {
var frm = $(this).closest('form');
var params = frm.serialize();
$.ajax({
type: 'POST',
url: '@Url.ApplicationAction("MyPostAction", "myController")',
data: params,
cache: false,
success: function (data) {
alert('Completed');
},
error: function (xhr, data, message) {
//console.log(data + ": " + message);
},
dataType: "json"
});
return false;
});
});
</script>
on server side model variable will have updated with all values submitted in form and will have following parameters:
[HttpPost]
public ActionResult MyPostAction(MyModel model)
{
return Json("Ok");
}
jquery events with example
Following example demonstrate how to use jQuery events:
To trigger event use this code :
Grid_CheckBox_Click is the name of my event.
to Subscribe to event use this code:
To trigger event use this code :
$document.trigger('Grid_CheckBox_Click',gridId,this);
Grid_CheckBox_Click is the name of my event.
to Subscribe to event use this code:
$(document).bind('Grid_CheckBox_Click', function (e, elem) {
MyFunction(e);
});
Thursday
mvc radiobuttonfor example
below is an example of creating mvc radio button control for boolean model myBoolProperty property
@Html.LabelFor( m => m.myBoolProperty)
@Html.RadioButtonFor(m => m.myBoolProperty, true)
@StringResources.Submitted
@Html.RadioButtonFor(m => m.myBoolProperty, false)
@StringResources.Fulfillment
Tuesday
mercurial server multiple repositories
Serving multiple repositories using hg serve
.
Here's my hgweb.config
file:
[paths]
project-a = C:/hg/project-a/
library-b = C:/hg/library-b/
I start hg serve
with this command:
hg serve --address 127.0.0.1 --port 8000 --webdir-conf C:/hg/hgweb.config --encoding utf8
Monday
Уроки
Урок 1 (он же главный): Найдите наикратчайший из способов удовлетворить потребность и не напрягайте пользователей деталями.
Нам через день предлагают добавить ту или иную фишку. Первый вопрос которым мы задаемся — а какому проценту наших пользователей это понадобиться. Если меньше 5% — мы этого делать не будем.
Урок 2 (вообще-то продолжение первого): ненужная большинству функциональность вредна поскольку усложняет понимание.
Вот как мы расправились с некоторыми из сложностей:
- Программа должна была работать с несколькими проектами/работами. Однако для большинства достаточно создать только один проект выбрав несколько баз для бэкапа. Мы сделали так, что программа сама открывает тот же проект, что и в прошлый раз и соединяется с тем же SQL сервером — так что большинство даже и не задумывается, что можно работать с несколькими проектами.
- SQL Connection String — до сих пор самая сложная часть для пользователя. При первом запуске мы, не спрашивая пользователя, перебираем самые распространенные Connection String, так что, открыв программу, большинство пользователей уже подключились к серверу и видят список своих баз данных.
- Посылка писем — чтобы не напрягать пользователей с настройкой SMTP мы по умолчанию посылаем письма через веб-сервис на своем сервере. Для бесплатных пользователей фишка бесплатна на неделю, а потом можно либо купить платную версию либо пользоваться своим Gmail или другим SMTP сервером.
- Расписание — большинству требуется Full Backup один раз в день. Что и можно сделать на основной форме. Для более продвинутых все настройки спрятаны за кнопкой Settings.
Деньги
Поработав немного, мы сделали первую версию программки. Далее мы поставили ее во все shareware-сайты и оставили комментарии на форумах по этой теме. Понемногу пошли клиенты. Через два месяца после выпуска нас заметила одна большая компания, продукт которой был основан на SQL и его пользователи с небольшими техническими знаниями были сами ответственны за бэкап. Для них мы подходили идеально и они послали всех своих пользователей к нам. Кроме этого они даже взяли на себя заботу по тех поддержке. Деньги потекли рекой.
Основная версия (Standard) стоит сейчас $59. Для тех компаний для которых это не деньги — у нас есть Professional с добавкой AES encryption за $69. Для экономных — Lite (максимум 5 баз данных) за $29. С год назад я прочитал какую-то статью о том, что цены на странице Prices нужно подавать от больших к малым дабы пользователю, испуганному первыми большими цифрами, цифра в середине показалась относительно скромной. Мы подумали: что бы такого выпустить дорогого чтобы пугать пользователей? Так родилась идея Lifetime-версии за $199 (сейчас $149) с бесплатными пожизненными обновлениями. И мы очень удивились когда ее стали бодро покупать!
Потом товарищ подкинул другую идею, которая принесла тысячи долларов. В добавок к продуктам мы продаем за небольшие деньги еще и Extended Support (тем, кто его купил — особое внимание при поддержке) и бесплатное обновление на 1 год (по умолчанию — 1 месяц). Дополнительные усилия близки к 0, а деньги понемногу капают…
Урок 3 — дайте пользователю заплатить столько, сколько он хочет и может.
Пиратство и жадность
С первых дней существования мы решили тратить только минимум времени на борьбу с пиратством. В программе зашит алгоритм на проверку лицензионного ключа который несложно взломать. Идея такова: если человек запускает keygen для взлома — он вряд ли заплатил бы за программу без этого. А так — будет пользоваться и, возможно, когда остепенится, тогда и почувствует потребность заплатить.
Многие устанавливают ключик на несколько машин — мы просто посылаем вежливые письма с напоминанием, что это неправильно. Компании в цивилизованных странах стараются договоренности соблюдать и покупают недостающие лицензии. С менее цивилизованными мы могли бы справиться добавив активацию, но это усложнило бы жизнь для большинства честных клиентов. И опять же: нами пользуются и это уже хорошо.
Урок 4 — концентрируйтесь на продукте, а не на защите. Пират сегодня — клиент завтра.
Большинству вполне хватает бесплатной версии в которой можно делать то же самое, что и в стандартной, только с ограничением в две базы данных. Благодарный народ даже пожертвования предлагает. Да мы и рады: когда потребности вырастут, тогда и заплатят, а заодно боремся с бесплатными самоделками.
Недавно мы добавили бэкапы в Amazon S3, Google Drive и Dropbox. Сначала было желание брать дополнительные деньги. Но решили не напрягать пользователей и просто добавить к существующим версиям. Будет больше пользователей — значит и доходы вырастут.
Урок 5 — довольные клиенты важнее сиюминутного наполнения карманов.
Friday
py2exe mechanize
I've got problem with including mechanize into py2exe package.
I resolved this problem by
Pomodoro technique game
I resolved this problem by
- uninstalling packages by running easy_install with -m key
easy_install -m mechanize
easy_install -m MultiPartPostHandler
- physically removing .eggs files from python2.X/site-packages/MYPACKAGE.egg
- installing packages with -Z key
easy_install.exe -Z mechanize
easy_install.exe -Z MultiPartPostHandler
Pomodoro technique game
Subscribe to:
Posts (Atom)
test smtp server with powershell
Send-MailMessage -SMTPServer smtp.domain.com -To [email protected] -From [email protected] -Subject "This is a test email" -Body ...
-
Here is instruction how to make blinking text in rainmeter: 1.right click and select " Edit skin " 2.add following code to temp...
-
Error:The element 'Schedule' has invalid child element 'RecurrenceRule'. List of possible elements expected: 'Occurring...
-
If you use Visual Studio to open a Web project that was developed for the .NET Framework 2.0, the .NET Framework 3.0, or the .NET Framework...