2014/12/04
2014/12/01
VBA current timestamp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function timestamp() As String | |
timestamp = Format(Now(), "yyyy-MM-dd hh:mm:ss") | |
End Function |
Generate Guid in VBA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function getGUID() As String | |
getGUID = Mid$(CreateObject("Scriptlet.TypeLib").GUID, 2, 36) | |
End Function |
How to connect to Sql Server local database file (localDB) with VBA ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sub run() | |
Dim conn As ADODB.Connection | |
Dim rs As ADODB.Recordset | |
Dim sqlStr As String | |
Dim dbFilePath As String | |
Dim dbName As String | |
dbName = "DbInjectorsCatalog" | |
dbFilePath = "C:\Users\marcinchyl\Desktop\Marcin2\Projects\InjectorsCatalog\Admin\DbInjectorsCatalog.mdf" | |
connStr = "Driver={SQL Server native Client 11.0};Server=(LocalDB)\v11.0;AttachDBFileName=" & dbFilePath & ";Database=" & dbName & ";Trusted_Connection=Yes" | |
sqlStr = "Select * from Injectors" | |
Set conn = New ADODB.Connection | |
conn.ConnectionString = connStr | |
conn.Open | |
Set rs = conn.Execute(sqlStr) | |
Do While Not rs.EOF | |
Debug.Print rs!Number | |
rs.MoveNext | |
Loop | |
rs.Close | |
Set rs = Nothing | |
End Sub |
2014/10/16
Cannot save changes to hosts file on Win7
a/ Run your editor as administartor -> Right click on Editor executable file (.exe) and choose option “Run as administartor”.
b/ Edit your file and save changes.
2014/10/04
How to install OpenCard on PHP host
1/ Downolad archive OpenCard from http://myopencart.com/downlaod -> http://sourceforge.net/projects/ocstore/files/latest/download
2/ Unzip and copy all its content to public_html folder (or any subfolder of that folder)
3/ Run page http://host/install/index.php
If it is not seen then you sholud change names of 3 php.ini files
/php.ini -> php.ini.txt
/admin/php.ini -> /admin/php.ini.txt
/install/php.ini -> /install/php.ini.txt
4/ On 1st screen
Confirm agreement terms
5/ On 2nd screen
change names of config files:
/config-dest.php -> config.php
/admin/config-dest.php -> /admin/config.php
6/ on 3rd screen give
database host: (sholudn't be localhost but external url)
database name:
database user:
user password:
if you don't yet created database then do it now
give credentials for admin account of the OpenCard
login: admin
password: .. (set this)
email: (set this)
7/ remove install directory
8/ If needed add:
DirectoryIndex index.html index.php
to .htaccess in main directory
to point that this is your default page.
9/ Download this file:
and copy to /system/database/
Give it this name: mmysqli.php
and change 2 lines in
/config.php
/admin/config.php
from define('DB_DRIVER', 'mysql');to define('DB_DRIVER', 'mmysqli');
2/ Unzip and copy all its content to public_html folder (or any subfolder of that folder)
3/ Run page http://host/install/index.php
If it is not seen then you sholud change names of 3 php.ini files
/php.ini -> php.ini.txt
/admin/php.ini -> /admin/php.ini.txt
/install/php.ini -> /install/php.ini.txt
4/ On 1st screen
Confirm agreement terms
5/ On 2nd screen
change names of config files:
/config-dest.php -> config.php
/admin/config-dest.php -> /admin/config.php
6/ on 3rd screen give
database host: (sholudn't be localhost but external url)
database name:
database user:
user password:
if you don't yet created database then do it now
give credentials for admin account of the OpenCard
login: admin
password: .. (set this)
email: (set this)
7/ remove install directory
8/ If needed add:
DirectoryIndex index.html index.php
to .htaccess in main directory
to point that this is your default page.
9/ Download this file:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
final class mMySQLi { | |
private $link; | |
public function __construct($hostname, $username, $password, $database) { | |
$this->link = new mysqli($hostname, $username, $password, $database); | |
if ($this->link->connect_error) { | |
trigger_error('Error: Could not make a database link (' . $this->link->connect_errno . ') ' . $this->link->connect_error); | |
} | |
$this->link->set_charset("utf8"); | |
$this->link->query("SET SQL_MODE = ''"); | |
} | |
public function query($sql) { | |
$query = $this->link->query($sql); | |
if (!$this->link->errno) { | |
if ($query instanceof mysqli_result) { | |
$data = array(); | |
while ($row = $query->fetch_assoc()) { | |
$data[] = $row; | |
} | |
$result = new stdClass(); | |
$result->row = isset($data[0]) ? $data[0] : array(); | |
$result->rows = $data; | |
$result->num_rows = $query->num_rows; | |
$query->close(); | |
return $result; | |
} else { | |
return true; | |
} | |
} else { | |
trigger_error('Error: ' . $this->link->error . '<br />Error No: ' . $this->link->errno . '<br />' . $sql); | |
} | |
} | |
public function escape($value) { | |
return $this->link->real_escape_string($value); | |
} | |
public function countAffected() { | |
return $this->link->affected_rows; | |
} | |
public function getLastId() { | |
return $this->link->insert_id; | |
} | |
public function __destruct() { | |
$this->link->close(); | |
} | |
} | |
?> |
Give it this name: mmysqli.php
and change 2 lines in
/config.php
/admin/config.php
from define('DB_DRIVER', 'mysql');to define('DB_DRIVER', 'mmysqli');
2014/09/03
How to append, add resource entry to resource .resx file in C#
Notice:
You need to add at least Read/Write permisions for NETWORK_SERWICE to .resx file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// helper class | |
public class ResEntry | |
{ | |
public string Entry { get; set; } | |
public string Message { get; set; } | |
} | |
/// <summary> | |
/// Method adds entries from resourceList to specified language resource file | |
/// </summary> | |
/// <param name="resDir">Cathalog where resources are stored</param> | |
/// <param name="resourceList"></param> | |
/// <param name="lang">Language prefix fg en - english, pl - polish, etc</param> | |
public void CreateNewsResourceEntry(string resDir, List<ResEntry> resourceList, string lang) | |
{ | |
string resxFile = Path.Combine(resDir, "News_." + lang + ".resx"); | |
List<ResEntry> currResList = new List<ResEntry>(); | |
using (ResXResourceReader resxReader = new ResXResourceReader(resxFile)) | |
{ | |
resxReader.UseResXDataNodes = true; | |
foreach (DictionaryEntry entry in resxReader) | |
{ | |
var node = (ResXDataNode)entry.Value; | |
//FileRef is null if it is not a file reference. | |
if (node.FileRef == null) | |
{ | |
var value = node.GetValue((ITypeResolutionService)null); | |
currResList.Add(new ResEntry() | |
{ | |
Entry = (string)node.Name, | |
Message = (string)value, | |
}); | |
} | |
} | |
} | |
currResList.AddRange(resourceList); | |
using (ResXResourceWriter resx = new ResXResourceWriter(resxFile)) | |
{ | |
foreach (var item in currResList) | |
resx.AddMetadata(item.Entry, item.Message); | |
resx.Generate(); | |
} | |
} | |
// usage example in ASP.NET | |
string resDir = Path.Combine(HttpRuntime.AppDomainAppPath, "App_GlobalResources"); | |
List<ResEntry> list = new List<ResEntry>(); in ASP.NET | |
list.Add(new ResEntry() { Entry = "Title_1", Message = "Title_1" }); | |
list.Add(new ResEntry() { Entry = "Message_1", Message = "Message_2" }); | |
Controller.CreateNewsResourceEntry(resDir, list, "en"); |
2014/08/31
Serialize / deserialize to xml extension methods in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static T Deserialize<T>(this T obj, string xmlFilePath) | |
{ | |
XmlSerializer serializer = new XmlSerializer(typeof(T)); | |
StreamReader reader = new StreamReader(xmlFilePath); | |
obj = (T)serializer.Deserialize(reader); | |
reader.Close(); | |
return obj; | |
} | |
public static void Serialize<T>(this T obj, string filePath) | |
{ | |
XmlSerializer writer = new XmlSerializer(typeof(T)); | |
StreamWriter file = new StreamWriter(filePath); | |
writer.Serialize(file, obj); | |
file.Close(); | |
} |
2014/08/28
How to convert string to enum in C# ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
order.Status = (OrderStatus) Enum.Parse(typeof(OrderStatus), "paid"); |
2014/08/26
How to create an element with attributes and a value but no sub-element using XmlSerializer ?
http://stackoverflow.com/questions/3524224/using-xmlserializer-to-create-an-element-with-attributes-and-a-value-but-no-sub
2014/08/24
Sending email using gmail smtp from Azure Cloud Service
Error:
Add to web.config:
http://stackoverflow.com/questions/11018233/cannot-use-gmail-smtp-from-azure-cloud-service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
System.Net.Mail.SmtpException: The SMTP server requires a secure connection | |
or the client was not authenticated. The server response was: | |
5.5.1 Authentication Required. Learn more at |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<system.net> | |
<mailSettings> | |
<smtp deliveryMethod="Network"> | |
<network defaultCredentials="false" enableSsl="true" host="smtp.gmail.com" port="587" userName="xxxxxxx@gmail.com" password="xxxxxxxxxxx"/> | |
</smtp> | |
</mailSettings> | |
</system.net> |
How to initialize Dictionary with default values in C# ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static Dictionary<int, string> GetProductsResponseErrors = new Dictionary<int,string>() | |
{ | |
{ 0, "Operation success" }, | |
{ 1, "Operation failed: invalid login or password." }, | |
{ 2, "Operation failed: access denied." }, | |
// .. | |
}; |
2014/08/22
Visual Studio 2013 - 'Operation Could Not Be Completed' when trying to open any View ?
I had two <appSeettings> nodes in config file.
Make only one node.
Maybe you will need restart of VS or system.
Make only one node.
Maybe you will need restart of VS or system.
How to backup SqlServer database ?
1/ Backup file: Right click on Database -> Task -> Backup ...
2/ Script with structure and data: Right click on Database-> Task -> Generate scripts -> On 3rd step of wizard choose 'Advanced' button and select 'Types of data to script':'Schema and data'.
2/ Script with structure and data: Right click on Database-> Task -> Generate scripts -> On 3rd step of wizard choose 'Advanced' button and select 'Types of data to script':'Schema and data'.
How to bind MVC model to different table ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ApplicationDBContext : DbContext | |
{ | |
public DbSet<ProductsModel> Products { get; set; } | |
protected override void OnModelCreating(DbModelBuilder modelBuilder) | |
{ | |
modelBuilder.Entity<ProductsModel>().ToTable("Products"); | |
// otherwise EF assumes the table is called "ProductsModel" | |
} | |
} |
Fatal error: Class 'SoapClient' not found in ..
1/ Open php.ini.
2/ Uncoment line:
from: ;extension=php_soap.dll
to: extension=php_soap.dll
3/ Restart php.
2/ Uncoment line:
from: ;extension=php_soap.dll
to: extension=php_soap.dll
3/ Restart php.
How to read config section from configuration file in C# ?
App.config
Class that reads config file.
Remember to add System.Configuration to Project references !
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8" ?> | |
<configuration> | |
<appSettings> | |
<add key="GateInvocationMax" value="10"/> | |
</appSettings> | |
</configuration> |
Remember to add System.Configuration to Project references !
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Configuration; | |
namespace Interlook.Common | |
{ | |
public class ConfigManager | |
{ | |
public static int GateInvocationMax | |
{ | |
get | |
{ | |
int gateInvocationMax = 10; | |
int.TryParse(ConfigurationManager.AppSettings["GateInvocationMax"], out gateInvocationMax); | |
return gateInvocationMax; | |
} | |
} | |
} | |
} |
2014/08/20
Lambda expression, return new elements of ToList() method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
IEnumerable<UserModel> users = db.Users.Select(it => new UserModel() { | |
Email = it.Email, | |
ForeName = it.ForeName, | |
Id = it.Id, | |
ModificationDate = it.ModificationDate, | |
//.. | |
}).ToList(); |
2014/08/19
How to change column name in sql server ?
EXEC SP_RENAME 'TableName.OldColumnName' , 'NewColumnName', 'COLUMN'
2014/08/18
How to generate random password, random string in C# ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static string GenaratePassword(int size = 8) | |
{ | |
string allowedChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
StringBuilder builder = new StringBuilder(size); | |
Random rnd = new Random(Environment.TickCount); | |
for (int i = 0; i < size; ++i) | |
builder.Append(allowedChars[rnd.Next(allowedChars.Length)]); | |
return builder.ToString(); | |
} |
2014/08/15
2014/08/13
Spf record example
Record SPF (Sender Policy Framework) allows you to check the host SMTP mail servers, the server sends e-mails from a given domain is authorized to do. It is in fact plain text record. To ensure compatibility with older implementations of servers / clients DNS domain should be 2 SPF records that contain exactly the same value, one type of SPF, and the second TXT.
Suppose, for example, that your domain example.com uses Gmail. You create an SPF record that identifies the mail servers as authorized Google Apps mail servers for that domain. When the recipient's mail server receives a message sent from the account user @ example.com, you may check the SPF record for the domain example.com, to determine if the message comes from an authorized mail server. If the message comes from a server other than the Google Apps mail servers listed in the SPF record, the recipient's mail server can reject it as spam.
If your domain has no SPF record, messages from users from that domain can be rejected by some of the recipients domain because it is not possible to check whether the message came from an authorized mail server.
Qualifiers
The qualifier is a single sign placed before the definition of the mechanism:
Qualifier | Description |
---|---|
"+" - PASS | indicates that the data source is authorized to send mail from the domain. If prior to the determination of the mechanism does not have a qualifier, it is assumed that it is "+". |
"?" - NEUTRAL | This source will be treated as if it was not him at all ... |
"~" - SOFTFAIL | Maile from this source will be rejected or accepted, but marked as SPAM. |
"-" - FAIL | Messages from this source will always be rejected. |
Mechanisms
Immediately after the qualifier is the "mechanism" that is, to identify the source:Mechanizm | Description |
---|---|
ip4: 192,168,137,101 | IPv4 Address - 192,168,137,101 |
ip6: 2001: db8 :: 1428: 57ab | Ipv6 Address - an Ipv6: 2001: db8 :: 1428: 57ab |
a | Each record for a domain |
mx | Each SMTP server accepting mail for this domain |
all | Each host on the Internet |
Examples
a/example.com. IN TXT "v = spf1 mx -all"
Each SMTP server is accepting mail for the domain przykladowa.local. may also be sent. Mail coming from other hosts across the Internet will be rejected.
b/
example.com. IN TXT "v = spf1 a -all"
Mail originating from any host in the domain will be accepted. On the other rejected.
c/
example.com. IN TXT "v = spf1 ip4:192,168,137,101 -all"
Incoming IP 192,168,168,137,101 will be accepted. Other messages rejected.
d/
example.com. IN TXT "v = spf1 a mx ip4:192,168,137,202 -all"
Incoming mail from any host in the domain, the SMTP server receiving the mail and IP 192,168,137,102 will be accepted. The remainder will be rejected.
e/
example.com. IN TXT "v = spf1 mx -ip4:192,168,137,101 -all"
Incoming mail from any SMTP server receiving the mail, bypassing the host IP 192,168,137,101 will be accepted. The remainder will be rejected.
Notes
Full syntax: http://www.openspf.org/SPF_Record_Syntax
Validator: http://www.kitterman.com/spf/validate.html
Generator: http://www.spfwizard.net/
How to add SPF in your domain: http://kb.mediatemple.net/questions/658/How+can+I+create+an+SPF+record+for+my+domain%3F#gs
2014/08/12
Enabling Visual Studio source code to public use..
Remember:
1. Add all external libraries and all "Copy locale" every .NET .dll
Solution -> Project -> References -> right click .dll -> Copy Local: True
2. ..
1. Add all external libraries and all "Copy locale" every .NET .dll
Solution -> Project -> References -> right click .dll -> Copy Local: True
2. ..
2014/08/11
Simple url construction example
http(s)://www.domain.net/site.php?arg1=val1&arg2=val2#label1
http(s) - protocol
www.domain.net - server address
site.php - document name (optional)
arg1,arg2 - url arguments passed to site (optional)
label1 - anchor, it points where to jump on site (optional)
http(s) - protocol
www.domain.net - server address
site.php - document name (optional)
arg1,arg2 - url arguments passed to site (optional)
label1 - anchor, it points where to jump on site (optional)
How to check your google search history ?
If you have google account and are logged in, google stores your search results in history.
Archive stores results even from some years ago.
To check your history visit:
https://history.google.com/history/
or where you were:
https://maps.google.com/locationhistory
2014/08/09
How to add and remove programs from startup windows 8 ?
Disable / enable program on startup Wndows 8
(right click) Windows Toolbar -> (select) Task Manager -> (select) Startup -> (right click) application -> (select) disable / enableAdd programs to startup Windows 8
From Run box run:%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup
or type in Windows explorer:
C:\Users\(your domain name)\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
or look here.
2014/08/04
How to force file update in TFS ?
1. Find file on drive and replace it with a new version
2. Open Team Explorer -> Source Control and find it in archive
3. Click right on file and select "Check out for edit"
4. Confirm changes as shown..
5. Now TFS knowsthat file needs to be updated in repository
6. Check In pending changes
2014/07/29
How to convert JSON object to Dictionary in C# ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static Dictionary<string, string> ConvertJsonStr2Dictionary(string jsonStr) | |
{ | |
Dictionary<string, string> dict = new Dictionary<string, string>(); | |
int start = jsonStr.IndexOf("{", 1) + 2; | |
int stop = jsonStr.LastIndexOf("}}"); | |
jsonStr = jsonStr.Substring(start, stop - start - 1); | |
string[] keyValArr = jsonStr.Split(new string[] { "," }, StringSplitOptions.None); | |
foreach(string keyVal in keyValArr) | |
{ | |
string key = RemoveLeadingEndingQuotationMarks(keyVal.Substring(0, keyVal.LastIndexOf(":")).Trim()); | |
string val = RemoveLeadingEndingQuotationMarks(keyVal.Substring(keyVal.LastIndexOf(":") + 1).Trim()); | |
dict.Add(key, val); | |
} | |
return dict; | |
} |
How to generate bitmap from url in C# ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static Bitmap GenerateScreenshot(string url, int width, int height) | |
{ | |
// Load the webpage into a WebBrowser control | |
WebBrowser wb = new WebBrowser(); | |
wb.ScrollBarsEnabled = false; | |
wb.ScriptErrorsSuppressed = true; | |
wb.Navigate(url); | |
while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } | |
// Set the size of the WebBrowser control | |
wb.Width = width; | |
wb.Height = height; | |
if (width == -1) | |
{ | |
// Take Screenshot of the web pages full width | |
wb.Width = wb.Document.Body.ScrollRectangle.Width; | |
} | |
if (height == -1) | |
{ | |
// Take Screenshot of the web pages full height | |
wb.Height = wb.Document.Body.ScrollRectangle.Height; | |
} | |
// Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control | |
Bitmap bitmap = new Bitmap(wb.Width, wb.Height); | |
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height)); | |
wb.Dispose(); | |
return bitmap; | |
} |
How to convert byte array to string and string to byte array in C# ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static byte[] GetByteArrayFromString(string s) | |
{ | |
byte[] bytes = new byte[s.Length * sizeof(char)]; | |
System.Buffer.BlockCopy(s.ToCharArray(), 0, bytes, 0, bytes.Length); | |
return bytes; | |
} | |
public static string GetStringFromByteArray(byte[] bytesArr) | |
{ | |
char[] chars = new char[bytesArr.Length / sizeof(char)]; | |
System.Buffer.BlockCopy(bytesArr, 0, chars, 0, bytesArr.Length); | |
return new string(chars); | |
} |
How to get HTML page content programatically in C# ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static string ReadPageContentFromUrl(string url) | |
{ | |
WebClient client = new WebClient (); | |
Stream data = client.OpenRead(url); | |
StreamReader reader = new StreamReader(data, Encoding.UTF8); | |
string html = reader.ReadToEnd(); | |
Encoding encFrom = Encoding.GetEncoding(readCharactersetFromHTML(html)); | |
html = ChangeEncoding(encFrom, Encoding.UTF8, html); | |
data.Close (); | |
reader.Close(); | |
return html; | |
} |
Polish NIP validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static bool ValidateNip(string nip) | |
{ | |
if (nip.Length != 10) return false; | |
try { Int64.Parse(nip); } | |
catch { return false; } | |
int[] weights = new int[] { 6, 5, 7, 2, 3, 4, 5, 6, 7 }; | |
int sum = 0; | |
for (int i = 0; i < weights.Length; i++) | |
sum += int.Parse(nip.Substring(i, 1)) * weights[i]; | |
return (sum % 11) == int.Parse(nip.Substring(9, 1)); | |
} |
Email address validation in C#
Not exacly compatible with iso:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static bool ValidateEmailAddress(string email) | |
{ | |
if (email.Length > 254) | |
return false; | |
else | |
{ | |
string[] emailParts = email.Split(new string[] { "@" }, StringSplitOptions.RemoveEmptyEntries); | |
if (emailParts.Length != 2 || email.StartsWith("@") || email.EndsWith("@") || (new Regex("[@]{2,}", RegexOptions.None)).IsMatch(email)) | |
return false; | |
else | |
{ | |
if (emailParts[0].Length <= 64) | |
{ | |
// alias | |
Regex rx1 = new Regex(@"^[a-zA-Z0-9_-][a-zA-Z0-9_\.-]*[a-zA-Z0-9_-]$", RegexOptions.None); | |
if (emailParts[0].Length > 64 || emailParts[0].Contains("..") || !rx1.IsMatch(emailParts[0])) | |
return false; | |
} | |
else | |
return false; | |
// domain | |
Regex rx2 = new Regex(@"^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\.[a-zA-Z]{2,63}$", RegexOptions.None); | |
if (emailParts[1].Contains("--") || !rx2.IsMatch(emailParts[1])) | |
return false; | |
} | |
} | |
return true; | |
} |
Convert datetime to timestamp and timestamp to datetime in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static readonly DateTime EpochUtc = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); | |
public static long ConvertDatetime2Timestamp(DateTime value) | |
{ | |
TimeSpan elapsedTime = value - EpochUtc; | |
return (long)elapsedTime.TotalSeconds; | |
} | |
public static DateTime ConvertTimestamp2Datetime(double timestampMilisec) | |
{ | |
DateTime dateTime = DateTime.SpecifyKind(EpochUtc, DateTimeKind.Utc); | |
return dateTime.AddSeconds(timestampMilisec); | |
} |
How to convert encoding from one to another in C# ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static string ChangeEncoding(Encoding encFrom, Encoding encTo, string srcStr) | |
{ | |
// Convert the string into a byte[]. | |
byte[] fromBytes = encFrom.GetBytes(srcStr); | |
// Perform the conversion from one encoding to the other. | |
byte[] toBytes = Encoding.Convert(encFrom, encTo, fromBytes); | |
// Convert the new byte[] into a char[] and then into a string. | |
// This is a slightly different approach to converting to illustrate | |
// the use of GetCharCount/GetChars. | |
char[] toChars = new char[encTo.GetCharCount(toBytes, 0, toBytes.Length)]; | |
encTo.GetChars(toBytes, 0, toBytes.Length, toChars, 0); | |
return new string(toChars); | |
} |
How to remove directory with all its files and subdirs recursively ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void DeleteDirCompletely(string dirPath) | |
{ | |
DirectoryInfo di = new DirectoryInfo(dirPath); | |
foreach (var file in di.GetFiles()) | |
File.Delete(file.FullName); | |
foreach (var dir in di.GetDirectories()) | |
Directory.Delete(dir.FullName); | |
Directory.Delete(dirPath); | |
} |
How to check if url is valid in C# ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public bool IsUrlValid(string url) | |
{ | |
string pattern = | |
@"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$"; | |
Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase); | |
return reg.IsMatch(url); | |
} |
How to compute MD5 in C# ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static string ComputeMd5(string input, bool convert2smallLetters = false) | |
{ | |
MD5 md5 = MD5.Create(); | |
byte[] inputBytes = Encoding.ASCII.GetBytes(input); | |
byte[] hash = md5.ComputeHash(inputBytes); | |
StringBuilder sb = new StringBuilder(); | |
for (int i = 0; i < hash.Length; i++) | |
{ | |
if (!convert2smallLetters) | |
sb.Append(hash[i].ToString("X2")); | |
else | |
sb.Append(hash[i].ToString("x2")); | |
} | |
return sb.ToString(); | |
} |
How to add column to table in TSQL ?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ALTER TABLE table_name | |
ADD column_name datatype | |
-- example | |
ALTER TABLE schClients.tSenders_ | |
ADD Confirmed BIT NOT NULL DEFAULT 0 | |
GO |
2014/07/20
Generate random number in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Random rnd = new Random(); | |
int dice = rnd.Next(1, 7); // creates a number between 1 and 6 | |
int card = rnd.Next(52); // creates a number between 0 and 51 |
2014/07/15
Insert Google Analitics code to Prestashop
Be carefull. You should not have any strings in your smarty template like this:
"{x.."
, because it's reserved for smarty variable and Prestashop uses smarty templates Instead use this:
"{ x...".
F.g:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-....', 'auto');
ga('send', 'pageview');
</script>
->
<script>
(function(i,s,o,g,r,a,m){ i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-....', 'auto');
ga('send', 'pageview');
</script>
"{x.."
, because it's reserved for smarty variable and Prestashop uses smarty templates Instead use this:
"{ x...".
F.g:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-....', 'auto');
ga('send', 'pageview');
</script>
->
<script>
(function(i,s,o,g,r,a,m){ i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-....', 'auto');
ga('send', 'pageview');
</script>
2014/07/14
How to read value returned by stored procedure - TSQL ?
http://msdn.microsoft.com/en-us/library/ms188332.aspx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DECLARE @ret INT | |
EXEC @ret = [schImports].[uspInsertImport] 1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE PROCEDURE [schImports].[uspInsertImport] (@importId int) | |
AS | |
BEGIN | |
-- ... | |
return @insertedNew; | |
END |
2014/07/07
Adding two integers without temporary variable - C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static void swamp(ref int x, ref int y) | |
{ | |
x = x + y; | |
y = x - y; | |
x = x - y; | |
} |
Read collection from configuration file app.config in C#
App.config:
Service classes:
Usage:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<configuration> | |
<configSections> | |
<section name="testConfig" type="Testy.ItemsConfigurationSection, Testy" /> | |
</configSections> | |
<testConfig> | |
<items> | |
<item name="One" /> | |
<item name="Two" /> | |
</items> | |
</testConfig> | |
</configuration> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Testy | |
{ | |
public class ItemConfigurationElement : ConfigurationElement | |
{ | |
[ConfigurationProperty("name", IsKey = true, IsRequired = true)] | |
public string Name | |
{ | |
get { return (string)this["name"]; } | |
} | |
} | |
[ConfigurationCollection(typeof(ItemConfigurationElement), AddItemName = "item")] | |
public class ItemsConfigurationElementCollection : ConfigurationElementCollection | |
{ | |
protected override ConfigurationElement CreateNewElement() | |
{ | |
return new ItemConfigurationElement(); | |
} | |
protected override object GetElementKey(ConfigurationElement element) | |
{ | |
return ((ItemConfigurationElement)element).Name; | |
} | |
} | |
public class ItemsConfigurationSection : ConfigurationSection | |
{ | |
[ConfigurationProperty("items", IsDefaultCollection = true)] | |
public ItemsConfigurationElementCollection Tests | |
{ | |
get { return (ItemsConfigurationElementCollection)this["items"]; } | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try | |
{ | |
ItemsConfigurationSection configManager = (ItemsConfigurationSection)ConfigurationManager.GetSection("testConfig"); | |
var zmienna = configManager.Tests; | |
} | |
catch (Exception ex) | |
{ | |
throw; | |
} |
Subscribe to:
Posts (Atom)