“No problem can be solved from the same level of consciousness that created it.” Albert Einstein (1879-1955)
Thursday, 5 December 2019
Wednesday, 27 November 2019
Enabling Non-Null Reference Types in VS Code
Add two new properties to any PropertyGroup: LangVersion and Nullable:
<PropertyGroup>
<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
Enable the annotation for nullable reference types
#nullable enable
string? name = null;
Friday, 4 October 2019
Getting API Data using XMLHttpRequest
<button id='get-btn' onclick='getData()'>GET</button>
const getBtn = document.getElementById('get-btn');
const getData = () => {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://reqres.in/api/users/');
xhr.responseType = 'json';
xhr.onload = () => {
console.log(xhr.response);
}
xhr.send();
}
getBtn.addEventListener('click', getData);
Sunday, 28 July 2019
Thursday, 4 July 2019
SQL Check Query Return Results
DECLARE @query nvarchar(MAX);
SET query = N'SELECT * FROM Table WHERE id=_id'
EXEC sp_executesql @queryToPass
IF ( @@ROWCOUNT > 0)
BEGIN
-- action
END
React Alert Popup (SweetAlert)
NPM: npm install sweetalert --save
CDN: <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
import swal from 'sweetalert';
const handleSignout = (e) => {
e.preventDefault();
swal({
title: '',
text: '',
icon: '',
dangerMode: true,
buttons: {
cancel: 'Cancel',
ok: 'OK'
}
}).then((result) => {
if (result) {
// actions
}
});
};
reference: https://github.com/t4t5/sweetalert
Tuesday, 2 July 2019
Prevents React App from Flash During Firebase/API Calls
const store = createStore(
rootReducer,
compose(
applyMiddleware(
thunk.withExtraArgument({
getFirestore,
getFirebase
})
),
reduxFirestore(fbConfig),
reactReduxFirebase(fbConfig, { attachAuthIsReady: true }),
window.__REDUX_DEVTOOLS_EXTENSION__
&& window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
store.firebaseAuthIsReady.then(() => {
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
});
Monday, 1 July 2019
React Routing
<BrowserRouter>
<Route exact path='/' component={LandingPage} />
<Route
path='/(.+)'
render={() => (
<div className='App'>
<Navbar />
<Switch>
<Route path='/route1' component={Component1} />
<Route path='/route2' component={Component2} />
<Route path='/route3' component={Component3} />
</Switch>
</div>
)}
/>
</BrowserRouter>
Tuesday, 25 June 2019
Sunday, 23 June 2019
React-Firebase Render Lists
state = { posts: {} };
async componentDidMount () {
await database.on('value', (snap) => {
this.setState({ posts: snap.val() });
});
}
renderPosts = () => {
if (this.state.posts !== null) {
const posts = this.state.posts;
return Object.keys(posts).map((key) => (
<div key={key}>
<h2>{posts[key].title}</h2>
<p>{posts[key].body}</p>
</div>
));
}
};
Sync React App with Firebase Real-time Database
---- fbConfig.js
import * as firebase from 'firebase';
var config = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: ''
};
firebase.initializeApp(config);
export default firebase;
---- App.js
import firebase from './fbCOnfig';
state = {
speed: 0
};
componentDidMount () {
const rootRef = firebase.database().ref().child('react');
const speedRef = rootRef.child('speed');
speedRef.on('value', (snap) => {
this.setState({ speed: snap.val() });
});
}
Saturday, 22 June 2019
Display Data in HTML using Firebase
<!DOCTYPE html>
<html>
<head>
<title>Sandbox</title>
<meta charset="UTF-8" />
<script
src="https://www.gstatic.com/firebasejs/6.2.2/firebase-app.js">
</script>
<script
src="https://www.gstatic.com/firebasejs/3.1.0/firebase-database.js">
</script>
</head>
<body>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
firebase.initializeApp(firebaseConfig);
var dbRef = firebase.database().ref().child('text');
dbRef.on('value', snap => console.log(snap.val()));
</script>
</body>
</html>
Wednesday, 29 May 2019
C# Encrypt and Decrypt String
public string Encrypt(string plainText)
{
try {
var sb = new System.Text.StringBuilder();
var bytes = System.Text.Encoding.Unicode.GetBytes(plainText);
foreach (var t in bytes)
sb.Append(t.ToString("X2"));
return sb.ToString();
}
catch {
return null;
}
}
public string Decrypt(string encryptedText)
{
try {
var bytes = new byte[encryptedText.Length / 2];
for (var i = 0; i < bytes.Length; i++)
bytes[i] = System.Convert.ToByte(encryptedText.Substring(i * 2, 2), 16);
return System.Text.Encoding.Unicode.GetString(bytes);
}
catch {
return null;
}
}
C# Get AD User Attribute
public string GetUserAttribute(string alias, string attribute)
{
try {
attribute = attribute.ToLower();
string propertyValue = null;
UserPrincipal user = UserPrincipal
.FindByIdentity(GetPrincipalContext,
IdentityType.SamAccountName, alias);
if (user != null)
{
//Create a searcher on your DirectoryEntry
DirectoryEntry directoryEntry = (user.GetUnderlyingObject()
as DirectoryEntry);
DirectorySearcher adSearch = new DirectorySearcher(directoryEntry);
//Look into all subtree during the search
adSearch.SearchScope = SearchScope.Subtree;
adSearch.Filter = "(&(ObjectClass=user)(sAMAccountName=" + alias + "))";
SearchResult sResult = adSearch.FindOne();
if (sResult.Properties.Contains(attribute))
propertyValue = sResult.Properties[attribute][0].ToString();
}
return propertyValue;
}
catch {
return null;
}
}
C# Get Logged-in User in IIS and IISExpress
public string LoggedInUserNetworkId()
{
string loggedinUser = WindowsIdentity.GetCurrent().Name; // IIS Express
loggedinUser = !string.IsNullOrEmpty(loggedinUser)
&& !loggedinUser.ToLower().Contains("apppool")
? loggedinUser
: HttpContext.Current.User.Identity.Name; // IIS
return
(!string.IsNullOrEmpty("Impersonate".GetValueFromConfig())
? "Impersonate".GetValueFromConfig()
: loggedinUser.Replace("DOMAIN\\", "")).PrettyWord();
}
public static string PrettyWord(this string word) =>
System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo
.ToTitleCase(word.Trim().ToLower());
Tuesday, 28 May 2019
Find Currently Running Query in SQL Server
SELECT
sqltext.TEXT,
req.session_id,
req.status,
req.start_time,
req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
Saturday, 20 April 2019
Setting up Basic Express Server
-- npm install express
// include express
const express = require('express');
const app = express();
// serve static files in Public folder
app.use(express.static('public'));
// run he server on port 2222
app.listen(2222, () => console.log('Server running on 2222...'));
// include express
const express = require('express');
const app = express();
// serve static files in Public folder
app.use(express.static('public'));
// run he server on port 2222
app.listen(2222, () => console.log('Server running on 2222...'));
Wednesday, 17 April 2019
Call JavaScript function after AJAX UpdatePanel Refresh (Partial PostBack) in ASP.Net
<asp:UpdatePanel runat="server">
<ContentTemplate>
Employee :
<asp:ListBox ID="lstEmployee" runat="server" SelectionMode="Multiple">
<asp:ListItem Text="Nikunj Satasiya" Value="1" />
<asp:ListItem Text="Dev Karathiya" Value="2" />
<asp:ListItem Text="Hiren Dobariya" Value="3" />
<asp:ListItem Text="Vivek Ghadiya" Value="4" />
<asp:ListItem Text="Pratik Pansuriya" Value="5" />
</asp:ListBox>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
window.onload = function () {
DrawEmployeeDDL();
};
//On UpdatePanel Refresh
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
prm.add_endRequest(function (sender, e) {
if (sender._postBackSettings.panelsToUpdate != null) {
DrawEmployeeDDL();
}
});
};
function DrawEmployeeDDL() {
$('[id*=lstEmployee]').multiselect({
includeSelectAllOption: true
});
};
</script>
<ContentTemplate>
Employee :
<asp:ListBox ID="lstEmployee" runat="server" SelectionMode="Multiple">
<asp:ListItem Text="Nikunj Satasiya" Value="1" />
<asp:ListItem Text="Dev Karathiya" Value="2" />
<asp:ListItem Text="Hiren Dobariya" Value="3" />
<asp:ListItem Text="Vivek Ghadiya" Value="4" />
<asp:ListItem Text="Pratik Pansuriya" Value="5" />
</asp:ListBox>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
window.onload = function () {
DrawEmployeeDDL();
};
//On UpdatePanel Refresh
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
prm.add_endRequest(function (sender, e) {
if (sender._postBackSettings.panelsToUpdate != null) {
DrawEmployeeDDL();
}
});
};
function DrawEmployeeDDL() {
$('[id*=lstEmployee]').multiselect({
includeSelectAllOption: true
});
};
</script>
Monday, 8 April 2019
React Apollo Boost & GraphQL Template Installer
{
"name": "project-name",
"version": "1.0.0",
"description": "A starter for React-Apollo-GraphQL projects",
"main": "server.js",
"scripts": {
"server": "nodemon server.js",
"client": "cd client && npm start",
"dev":
"concurrently --names \"server,client\" \"npm run server --silent\" \"npm run client --silent\""
},
"author": "",
"license": "ISC",
"dependencies": {
"apollo-server-express": "^1.3.6",
"bcrypt": "^2.0.1",
"body-parser": "^1.18.3",
"concurrently": "^3.5.1",
"cors": "^2.8.4",
"dotenv": "^5.0.1",
"express": "^4.16.3",
"graphql": "^0.13.2",
"graphql-tools": "^3.0.2",
"jsonwebtoken": "^8.2.1",
"mongoose": "^5.1.3"
},
"devDependencies": {
"nodemon": "^1.17.5"
}
}
"name": "project-name",
"version": "1.0.0",
"description": "A starter for React-Apollo-GraphQL projects",
"main": "server.js",
"scripts": {
"server": "nodemon server.js",
"client": "cd client && npm start",
"dev":
"concurrently --names \"server,client\" \"npm run server --silent\" \"npm run client --silent\""
},
"author": "",
"license": "ISC",
"dependencies": {
"apollo-server-express": "^1.3.6",
"bcrypt": "^2.0.1",
"body-parser": "^1.18.3",
"concurrently": "^3.5.1",
"cors": "^2.8.4",
"dotenv": "^5.0.1",
"express": "^4.16.3",
"graphql": "^0.13.2",
"graphql-tools": "^3.0.2",
"jsonwebtoken": "^8.2.1",
"mongoose": "^5.1.3"
},
"devDependencies": {
"nodemon": "^1.17.5"
}
}
Thursday, 4 April 2019
JQuery Datatable add View Edit Delete Column in ASP.NET
"fnDrawCallback": function () {
jQuery(element).find('thead tr th:last-child').replaceWith("<th>View / Edit</th>");
jQuery(element).find('tbody tr').each(function () {
var courseID = $(this).find('td:first-child').html();
var links = "<a href='/view?id={{courseID}}'></a>";
$(this).find("td:last-child:not(:first-child)").replaceWith("<td>" + links.replace(/{{courseID}}/g, courseID) + "</td>");
});
}
CSS to position search and page drop downlist:
.dataTables_filter {
float: left !important;
text-align: left !important;
}
.dataTables_length {
float: right !important;
text-align: right !important;
}
jQuery(element).find('thead tr th:last-child').replaceWith("<th>View / Edit</th>");
jQuery(element).find('tbody tr').each(function () {
var courseID = $(this).find('td:first-child').html();
var links = "<a href='/view?id={{courseID}}'></a>";
$(this).find("td:last-child:not(:first-child)").replaceWith("<td>" + links.replace(/{{courseID}}/g, courseID) + "</td>");
});
}
CSS to position search and page drop downlist:
.dataTables_filter {
float: left !important;
text-align: left !important;
}
.dataTables_length {
float: right !important;
text-align: right !important;
}
Wednesday, 3 April 2019
Git Credential Manager for Windows Popups
- Installed Git Credential Manager for Windows
- Opened the terminal by clicking the Terminal button in SourceTree.
- Issued the commands below:
- git config --global credential.helper manager
- git config --global credential.useHttpPath true
Tuesday, 2 April 2019
JQuery Datatable with Update Panel in ASP.NET
</head>
<body>
<form runat="server">
<asp:ScriptManager runat="server">
...
</form>
<script>
$(document).ready(function () {
// bind data table on first page load
bindDataTable();
// bind data table on every UpdatePanel refresh
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(bindDataTable);
});
function bindDataTable() {
// Apply DataTable library
jQuery('.datatable-sortable').hide().each((index, element) => {
jQuery(element)
.prepend(jQuery("<thead></thead>")
.append(jQuery(element).find("tbody tr:first")))
.dataTable(
{
"oLanguage": {
"sLengthMenu": "Show _MENU_",
},
"order": [],
"iDisplayLength": 20,
"aLengthMenu": [[-1, 10, 20, 30, 50, 100, 200], ["All", 10, 20, 30, 50, 100, 200]],
"fnInitComplete": function () {
jQuery(element)
.show()
.addClass("hover")
.addClass("compact")
.addClass("nowrap");
}
});
});
}
</script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"/>
<script type="text/javascript" src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
</body>
<body>
<form runat="server">
<asp:ScriptManager runat="server">
...
</form>
<script>
$(document).ready(function () {
// bind data table on first page load
bindDataTable();
// bind data table on every UpdatePanel refresh
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(bindDataTable);
});
function bindDataTable() {
// Apply DataTable library
jQuery('.datatable-sortable').hide().each((index, element) => {
jQuery(element)
.prepend(jQuery("<thead></thead>")
.append(jQuery(element).find("tbody tr:first")))
.dataTable(
{
"oLanguage": {
"sLengthMenu": "Show _MENU_",
},
"order": [],
"iDisplayLength": 20,
"aLengthMenu": [[-1, 10, 20, 30, 50, 100, 200], ["All", 10, 20, 30, 50, 100, 200]],
"fnInitComplete": function () {
jQuery(element)
.show()
.addClass("hover")
.addClass("compact")
.addClass("nowrap");
}
});
});
}
</script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css"/>
<script type="text/javascript" src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
</body>
Subscribe to:
Posts (Atom)
SQL: Generate a range of numbers
SELECT ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n), (VALU...
-
//convert BASE64 string to Byte{} array function base64ToArrayBuffer(base64) { var binaryString = window.atob(base64); var binar...
-
static void Main(string[] args) { // create a dummy list List<string> data = GetTheListOfData(); // split the lis...
-
var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter(); htmlToPdf.PageFooterHtml = @"<div style='text-align:right; font-s...