- using Microsoft.AspNetCore.Http;
- /// <summary>
- /// Get the cookie
- /// </summary>
- /// <param name=”key”>Key </param>
- /// <returns>string value</returns>
- public string GetCookie(string key)
- {
- return Request.Cookies[key];
- }
- /// <summary>
- /// set the cookie
- /// </summary>
- /// <param name=”key”>key (unique indentifier)</param>
- /// <param name=”value”>value to store in cookie object</param>
- /// <param name=”expireTime”>expiration time</param>
- public void SetCookie(string key, string value, int? expireTime)
- {
- CookieOptions option = new CookieOptions();
- if (expireTime.HasValue)
- option.Expires = DateTime.Now.AddMinutes(expireTime.Value);
- else
- option.Expires = DateTime.Now.AddMilliseconds(10);
- Response.Cookies.Append(key, value, option);
- }
- /// <summary>
- /// Delete the key
- /// </summary>
- /// <param name=”key”>Key</param>
- public void RemoveCookie(string key)
- {
- Response.Cookies.Delete(key);
- }
Category Archives: asp.net
Cookie in ASP.NET Core
Chart JS | dynamic Data
//make sure to add Jquery and Chartjs Library
a canvas with id=”seolinechart”
//inside script tag START
$.get(“functions.aspx?cat=GETData”, function (data, status) {
if (status == “success”) {
if ($(‘#seolinechart’).length) {
var ctx = document.getElementById(“seolinechart”).getContext(‘2d’);
var businessUnits = [];
var bgColor = [“#8919FE”, “#12C498”, “#F8CB3F”, “#E36D68”, “#a2fe19”, “#199bfe”, “#d419fe”, “#fe6919”, “#d8fe19”, “#fe198f”];
var contractCount = [];
var contractValue = [];
var totalCount = 0;
var contractData = JSON.parse(data);
for (i = 0; i < contractData.length; i++) {
businessUnits[i] = contractData[i].Business_Unit_CRM;
contractCount[i] = contractData[i].Count;
contractValue[i] = contractData[i].Contract_TotalAmount_KWD;
totalCount = totalCount + parseInt(contractData[i].Count);
}
var chart = new Chart(ctx, {
// The type of chart we want to create
type: ‘pie’,
// The data for our dataset
data: {
labels: businessUnits,
datasets: [{
backgroundColor: bgColor,
borderColor: ‘#fff’,
data: contractCount,
}]
},
// Configuration options go here
options: {
title: {
display: true,
position: ‘bottom’,
text: ‘Total Contracts:’ + totalCount
},
legend: {
display: true,
},
animation: {
easing: “easeInOutBack”
},
tooltips: {
// Disable the on-canvas tooltip
enabled: true,
bodyFontSize: 14,
callbacks: {
label: function (tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label || ”;
//console.log(tooltipItem);
//console.log(data);
//console.log(data.labels[4]);
if (label) {
label += ‘: ‘;
}
// label += Math.round(tooltipItem.yLabel * 100) / 100;
label += data.labels[tooltipItem.index] + ‘: (‘ + data.datasets[0].data[tooltipItem.index] + ‘) KWD ‘ + parseInt(contractValue[tooltipItem.index]).toString().replace(/\B(?=(\d{3})+(?!\d))/g, “,”); //.toFixed(3).replace(/\d(?=(\d{3})+\.)/g, ‘$&,’);
return label;
}
}
}
}
});
}
}
});
//script tag END
Delete all or n Rows from a table Entity Framework
write a method DeleteAll in your table repository class, if one is there.
public void DeleteAll()
{
table1Repository.Entities.table1.RemoveRange(table1Repository.Entities.table1.AsEnumerable().Where(cb => cb.Id > 0));
table1Repository.Entities.SaveChanges();
}
Create session in database in MSSQL
Find the folder containing aspnet_regsql file, probably C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_regsql.go to this folder from command prompt(CMD)
cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
execute the command : ASPNET_REGSQL.EXE -S localhost -U sa -P MyPassword -ssadd -sstype p
replace ‘sa’ with database username and ‘MyPassword’ with database password.
Then go to IIS and select the website and go to Session State (in ASP.NET tab).
select SQL Server option and set the connection string. Provide the database username password of the ASPState database.
APPLY the settigns and browse your website.
if a new record is entered in ASPState database >ASPStateTempSessions table, your session works perfect!
- if you want to increase the session time out, go to the Application pool of your website in IIS > Advanced Settings and set the Idle-Timeout (Minutes) in Process Model tab to desired value. (default value is 20)
file in iframe downloads automatically on page load
To Prevent the file in iframe from auto download on page load, remove assigning src property of iframe on page load.
ASPxCaptcha image not loading in load balancer with multiple servers; DXB.axd resource not found;
In Load balanced servers, move the session to database. After that set the challange image binary storeage mode to session for Captcha control, else one servers wont load the captcha image loaded by another server on previous page load attempt
<dx:ASPxCaptcha ID=”ASPxCaptcha1″ runat=”server” Width=”250px” CharacterSet=”23456789ABCDEFGH”
CodeLength=”3″ TextBox-Position=”Bottom” ChallengeImage-BackgroundColor=”#1278C2″
ChallengeImage-ForegroundColor=”White” ChallengeImage-BinaryStorageMode=”Session”>
</dx:ASPxCaptcha>
Chat option with Zen Desk
if you have a paid account,login to the account with credentials . The url may look like : https://USERNAME.zendesk.com/access/unauthenticated
After that you have to add a script in head tag of your webpage. To get that script, follow the path below:
Admin (in left side menu)> Channels section > Widget > Setup tab.
Paste the code in the head tag and you will have the chat option in your website.
Web.config in sub folder
Root folder web.config
<?xml version=”1.0″?>
<configuration>
<system.web>
<compilation debug=”true” targetFramework=”4.0″ />
</system.web>
<appSettings>
<add key=”root” value=”This is from root web.config”></add>
<add key=”MySetting” value=”This my settings is from root web.config”></add>
</appSettings>
<connectionStrings>
<add name=”ConnectionString” connectionString=”Data Source=000.00.00.00;Initial Catalog=db;User ID=dbuser;Password=dbpassword;”/>
</connectionStrings>
</configuration>
Sub folder Web.config
<?xml version=”1.0″?>
<configuration>
<system.web>
</system.web>
<appSettings>
</appSettings>
</configuration>
Push Notification APNS-IOS
using System.Security.Authentication;
using System.Security.Cryptography.X509Certifica
public bool SendPushNotificationIos(string UserName, string Message, string DeviceId, int? badge)
{
int port = 2195;
// string hostname = “gateway.sandbox.push.apple.com”;
string hostname = “gateway.push.apple.com”;
var clientCertificate = new X509Certificate2(Server.MapPath(“/Certificates/iosapns-dev-cert.p12”), “xxpasswordxx”, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
TcpClient client = new TcpClient(hostname, port);
SslStream sslStream = new SslStream(
client.GetStream(),
false,
new RemoteCertificateValidationCallback(ValidateServerCertificate),
null
);
try
{
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls12, true);
}
catch (AuthenticationException ex)
{
client.Close();
//continue;
}
// Encode a test message into a byte array.
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0); //The command
writer.Write((byte)0); //The first byte of the deviceId length (big-endian first byte)
writer.Write((byte)32); //The deviceId length (big-endian second byte)
writer.Write(HexToData(DeviceId.ToUpper()));
byte[] byteArray = Encoding.ASCII.GetBytes(DeviceId.ToUpper());
string alert = “alert”;
string sound = “silent.aif”;
String payload = ” {\”aps\”: {\”alert\” : {\”title\” : \”” + alert + “\”, \”body\” : \”” + Message + “\”}, \”badge\”:” + badge + “, \”sound\”: \”” + sound + “\”, }, \”vibrate\”: true}”;
writer.Write((byte)0); //First byte of payload length; (big-endian first byte)
writer.Write((byte)payload.Length); //payload length (big-endian second byte)
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
sslStream.Flush();
// Close the client connection.
client.Close();
return true;
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine(“Certificate error: {0}”, sslPolicyErrors);
// Do not allow this client to communicate with unauthenticated servers.
return false;
}
private static byte[] HexToData(string deviceId)
{
if (deviceId == null)
return null;
if (deviceId.Length % 2 == 1)
deviceId = ‘0’ + deviceId; // Up to you whether to pad the first or last byte
byte[] data = new byte[deviceId.Length / 2];
for (int i = 0; i < data.Length; i++)
data[i] = Convert.ToByte(deviceId.Substring(i * 2, 2), 16);
return data;
}
Push FCM Notification
using System.Web.Script.Serialization;
public void AndroidNotify(string applicationID, string senderId, string deviceId)
{
WebRequest tRequest = WebRequest.Create(“https://fcm.googleapis.com/fcm/send“);
tRequest.Method = “post”;
tRequest.ContentType = “application/json”;
var data = new
{
to = deviceId,
notification = new
{
body = “Asp Notification To Device” + DateTime.Now.ToLocalTime().ToString(),
title = “Notification”,
icon = “myicon”
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format(“Authorization: key={0}”, applicationID));
tRequest.Headers.Add(string.Format(“Sender: id={0}”, senderId));
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
string str = sResponseFromServer;
Response.Write(“Response:” + str);
}
}
}
}
}