AnnotationChart dateformat from sqlserver - sql

Hi Im trying to implement an Annotation chart that get its data from Sql Server. The code is working as the data is coming back . My problem is the format of the date / datetime when doing google.visualization.DataTable().addRow()
The date format returned from sqlserver is 2014-03-19 12:00:00 AM
How to change this date format to insert into the datatable.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script type='text/javascript' src='http://www.google.com/jsapi'></script>
<script type="text/javascript">
google.load('visualization', '1.1', { packages: ['annotationchart'] });
</script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: 'Default.aspx/GetData',
data: '{}',
success:
function (response) {
drawVisualization(response.d);
}
});
})
function drawVisualization(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Column Name');
data.addColumn('number', 'Column Value');
data.addColumn('number', 'Column Value2');
console.log(dataValues[0].ColumnName);
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].ColumnName, dataValues[i].Value, dataValues[i].Value2]);
}
var formatter = new google.visualization.DateFormat({pattern: 'yyyy-MM-dd'});
var chart = new google.visualization.AnnotationChart(document.getElementById('visualization'));
var options = {
displayAnnotations: false,
};
chart.draw(data, options);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="visualization" style="width: 1000px; height: 500px;">
</div>
</form>
</body>
</html>
This is the C# code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<Data> GetData()
{
SqlConnection conn = new SqlConnection(****);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
conn.Open();
string cmdstr = "select LogDate, val1, val2from [vwTest]";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
dt = ds.Tables[0];
List<Data> dataList = new List<Data>();
string cat = "";
int val = 0;
int val2 = 0;
foreach (DataRow dr in dt.Rows)
{
cat = dr[0].ToString();
val = Convert.ToInt32(dr[1]);
val2 = Convert.ToInt32(dr[2]);
DateTime dte = DateTime.Parse(DateTime.Parse(cat).ToString("yyyy-MM-dd"));
dataList.Add(new Data(dte, val, val2));//Dont know what to do here
}
return dataList;
}
public class Data
{
public DateTime ColumnName;
public int Value = 0;
public int Value2 = 0;
public Data(DateTime columnName, int value, int value2)
{
ColumnName = columnName;
Value = value;
Value2 = value2;
}
}
}
I see examples where people use new Date(2013,23,3,4,5) say but im not hard coding my data.
Please assist. This is my first Attempt at Google Visualization API

Dates are tricky to work with when you are sending data via JSON (since JSON does not have a date standard). The only way to get them input as proper Date objects is to use the full JSON DataTable syntax for specifying rows, columns, and cells of data. Since I'm not quite sure how this would be done in C#, I have an alternative approach I can demonstrate for you. Since you need Date objects for your DataTable, and your output is giving you date strings, it is a relatively simple task to parse the strings into year, month, and day, and then build a Date object from those:
for (var i = 0; i < dataValues.length; i++) {
// assumes the date string is in the format "yyyy-MM-dd"
var dateArr = dataValues[i].ColumnName.split('-');
var year = dateArr[0];
var month = dateArr[1] - 1; // adjust for javascript's 0-indexed months
var day = dateArr[2];
data.addRow([new Date(year, month, day), dataValues[i].Value, dataValues[i].Value2]);
}

Related

Blazor Server - Return Count from SQL - Returns System.Collections.Generic.List`1[System.Object]

I'm trying to return a count of row's from a stored procedure in SQL. I've been working at this for hours now. I'm at a complete loss.
SQL Code: Returns result of 49 when run in SQL.
begin
select Count (EmployeeID)
from dbo.Employees
Where (Employees.Active = 'True')
end
Component Code:
#attribute [Authorize(Roles = "Admin")]
#using System.Collections;
#using WahlenDataAccessLibrary;
#using WahlenDataAccessLibrary.Models;
#using BlazorApp1.Models;
#inject IEmployeesData employeeData;
<div class="widget">
<h5 class="widget--title">Active Employees</h5>
<div class="widget--body">
<p class="widget--number">
<span>#employeeCount</span>
Active Employees
</p>
</div>
</div>
#code {
private string employeeCount { get; set; }
//private IEmployeeModel employeeCount = new EmployeeModel();
protected override async Task OnInitializedAsync()
{
var count = await employeeData.EmployeeCount();
//string employeeCount = await employeeData.EmployeeCount();
string employeeCount = count.ToString();
Console.WriteLine(employeeCount);
if (employeeCount != null)
{
Console.WriteLine("generic value");
}
else
{
Console.WriteLine("no value");
}
}
}
DataFile Code: To get the value from stored procedure.
public async Task<string> EmployeeCount()
{
var employeeCount = await _db.LoadValue("dbo.spWidget_EmployeeCount", "DefaultConnection");
return employeeCount.ToString();
}
}
The DataFile where 'LoadValue' is used. This is linked back to my SqlDataAccess File which uses this code.
public async Task<string> LoadValue(string storedProcedure, string connectionStringName)
{
string connectionString = _config.GetConnectionString(connectionStringName);
using (IDbConnection connection = new SqlConnection(connectionString))
{
var data = await connection.QueryAsync(storedProcedure,
commandType: CommandType.StoredProcedure);
return data.ToString();
}
}
When the application is running the console writes.
System.Collections.Generic.List`1[System.Object]
no value
The
System.Collections.Generic.List`1[System.Object]
comes from
var data = await connection.QueryAsync(storedProcedure,
commandType: CommandType.StoredProcedure);
return data.ToString();
the var data is actually an object. Callint .ToString() on a object will print out the type of the object (if the method is not over written).
Please check if the QueryAsync has a generic version. Usually it does and will make a type cast for you in the background. Try something like QueryAsync<int>. Or try to find the rigth method (with a single return item, instead of a list) on your ORM/db provider.
From the current context it is not possible to tell what db provider you are using.
I'm going to update the code here, as I've got it working.
Task<IEnumerable> was more so the answer here. If you have an sql query that is simply counting rows, this is how you access that data on Blazor on your front end. You can return the value as a string.
My sqlaccess file code now looks like this.
public async Task<IEnumerable<int>> LoadValue(string storedProcedure, string connectionStringName)
{
string connectionString = _config.GetConnectionString(connectionStringName);
using (IDbConnection connection = new SqlConnection(connectionString))
{
var data = await connection.QueryAsync<int>(storedProcedure,
commandType: CommandType.StoredProcedure);
return data;
}
}
And this is on the front end component.
private string employeeCount { get; set; }
protected override async Task OnInitializedAsync()
{
employeeCount = await employeeData.EmployeeCount();
Console.WriteLine(employeeCount);
if (employeeCount != null)
{
Console.WriteLine("generic value");
}
else
{
Console.WriteLine("no value");
}

.Net Core Equivalent to CryptoJS.AES.encrypt

I have below JavaScript code that uses CryptoJS.AES.encrypt function from CryptoJS library and I am looking for equivalent .Net Core code, can anyone please guide?
var myData = '';
var key1 = '';
var key2 = '';
var encryptedData = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(myData.substr(0, myData.length - 1)), CryptoJS.enc.Utf8.parse(key1),
{
keySize: 128 / 8,
iv: CryptoJS.enc.Utf8.parse(key2),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
Edit
I have found below code for .Net Core:
public string EncryptString(string text, string keyString, string ivString)
{
var key = Encoding.UTF8.GetBytes(keyString);
using (var aesAlg = Aes.Create())
{
using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
{
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(text);
}
var iv = aesAlg.IV;
var decryptedContent = msEncrypt.ToArray();
var result = new byte[iv.Length + decryptedContent.Length];
Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length);
return Convert.ToBase64String(result);
}
}
}
}
But I am not sure how to specify these options as specified in JavaScript code:
{
keySize: 128 / 8,
iv: CryptoJS.enc.Utf8.parse(key2),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
}
Edit 2
I updated my C# code following suggestions from Topaco and below is my code.
But when I test it the output of my C# code and JavaScript code is different can anyone please guide what's missing?
public string RequestHash(string text, string keyString, string ivString)
{
var key = Encoding.UTF8.GetBytes(keyString);
var iv = Encoding.UTF8.GetBytes(ivString);
using (var aesAlg = Aes.Create())
{
using (var encryptor = aesAlg.CreateEncryptor(key, iv))
{
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(text);
}
var decryptedContent = msEncrypt.ToArray();
return Convert.ToBase64String(decryptedContent);
}
}
}
}
Thank you so much Topaco for your help, really appreciate!
Here's my final code:
public string RequestHash(string text, string keyString, string ivString)
{
var key = Encoding.UTF8.GetBytes(keyString);
var iv = Encoding.UTF8.GetBytes(ivString);
using (var aesAlg = Aes.Create())
{
using (var encryptor = aesAlg.CreateEncryptor(key, iv))
{
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(text);
}
var decryptedContent = msEncrypt.ToArray();
return Convert.ToBase64String(decryptedContent);
}
}
}
}

I want to insert link into my images which come from database and fetch to their related data using asp.net

In my SQL Server I wrote a stored procedure which take BrandName and searches it and returns related records. It work properly.
But in view were I make images and insert link on it and when click on the image it sent its name and other side it used for search in my code only last image tag worked properly, when I click other images then it give error DBNull error...
View
#model IEnumerable<BusinessLayer.Entities.ProductDetail>
<div class="row">
#foreach (var item in Model)
{
<div>
<img src="~/Images/Brands/#item.BrandImage" width="100" height="100" />
</div>
}
</div>
In repository
public IEnumerable<ProductDetail> BrandData(string BrandName)
{
SqlCommand cmd = new SqlCommand("searchinthebaseofBrand", DACUtil.getConnection());
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#BrandName", BrandName);
List<ProductDetail> pd = null;
using (SqlConnection con = cmd.Connection)
{
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.HasRows)
{
pd = new List<ProductDetail>();
while (sdr.Read())
{
ProductDetail pro = new ProductDetail()
{
ProductDetail_Id = Convert.ToInt32(sdr["ProductDetail_Id"]),
ProductName = Convert.ToString(sdr["ProductName"]),
ProductDescription = Convert.ToString(sdr["ProductDescription"]),
};
pd.Add(pro);
}
pd.TrimExcess();
}
}
return pd;
}
In controller
public ActionResult Manufacture(string BrandName)
{
if (BrandName == null)
{
return HttpNotFound();
}
return View(context1.BrandData(BrandName));
}
When I click other images not last one it give me following error:
I think that your method is not filling in the BrandImage or the BrandName property so it is defaulting to null
ProductDetail pro = new ProductDetail()
{
ProductDetail_Id = Convert.ToInt32(sdr["ProductDetail_Id"]),
ProductName = Convert.ToString(sdr["ProductName"]),
ProductDescription = Convert.ToString(sdr["ProductDescription"]),
BrandImage = = Convert.ToString(sdr["BrandImage"]),
BrandName = = Convert.ToString(sdr["BrandName"]),
};

Form post passes null model - .NET MVC 4

I am using this post as reference
I am trying to get the Model that I passed to the view to post back to the HttpPost method of the controller when the input is clicked. However, the model, which in this case is just List, is null when it posts back.
I have included my code for reference. This is just a project for testing random stuff out so I apologize for the crappy code.
I have the following View code: (showing the whole code for completness)
#{
ViewBag.Title = "Home Page";
}
#using TestApp.MyObjects
#model List<Contact>
#Ajax.ActionLink("Show About", "About", new { id = "1" }, new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "contentDiv" })
#Ajax.ActionLink("Show Contact", "Contact", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "contentDiv" })
<div id="contentDiv"></div>
#using (Html.BeginForm())
{
<table>
#foreach (Contact c in Model)
{
<tr>
<td>
<button aboutnum0 = "#c.someValues[0]" aboutnum1 = "#c.someValues[1]" aboutnum2 = "#c.someValues[2]" class="nameButton">#c.name</button>
</td>
</tr>
}
</table>
<input value="#Model[0].name" />
<input value="#Model[0].name" />
<div id ="aboutContentDiv"></div>
<input type="submit" />
#ViewBag.myCoolValue
}
<script type="text/javascript">
$("button").click(function () {
$("#aboutContentDiv").empty();
$("#aboutContentDiv").append($("<div></div>").load("Home/About/" + $(this).attr("aboutnum0")));
$("#aboutContentDiv").append($("<div></div>").load("Home/About/" + $(this).attr("aboutnum1")));
$("#aboutContentDiv").append($("<div></div>").load("Home/About/" + $(this).attr("aboutnum2")));
});
</script>
The Following is my Comtroller Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestApp.MyObjects;
namespace TestApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
Contact c = new Contact();
c.name = "Some Name";
c.someValues = new List<string>();
c.someValues.Add("1");
c.someValues.Add("2");
c.someValues.Add("3");
Contact c1 = new Contact();
c1.name = "Some Name1";
c1.someValues = new List<string>();
c1.someValues.Add("4");
c1.someValues.Add("5");
c1.someValues.Add("6");
Contact c2 = new Contact();
c2.name = "Some Name2";
c2.someValues = new List<string>();
c2.someValues.Add("7");
c2.someValues.Add("8");
c2.someValues.Add("9");
List<Contact> clist = new List<Contact>();
clist.Add(c);
clist.Add(c1);
clist.Add(c2);
Session["myCoolValue"] = "Cool1";
TempData["myCoolValue"] = "Cool2";
return View(clist);
}
[HttpPost]
public ActionResult Index(List<Contact> contacts)
{
string name = contacts[0].name;
return View("Index",contacts);
}
public PartialViewResult About(string id = "")
{
ViewBag.Message = "Your app description page.";
About a = new About();
a.someValue = id + " _ modified by contoller";
ViewBag.myCoolValue = "Cool";
return PartialView("About",a);
}
public PartialViewResult Contact()
{
ViewBag.Message = "Your contact page.";
return PartialView("Contact");
}
}
}
Based on your reply to my comment, you need something like this:
// you can use foreach and have a counter variable or this
for (int i = 0; i < Model.Count; i++)
{
// you do not want to use a partial view so let's do it this way
// put this in an appropriate place in your code
// like inside a tr or div, it's up to you
#Html.TextboxFor(m => m[i].name)
}

How to encrypt the query string ID in MVC 4 ActionLink

How can I pass the encrypted id in ActionLink. This is what I have written in my view:
#model IEnumerable<forumAPP.tblTechnology>
#foreach (var item in Model)
{
string techName=item.TechName;
#Html.ActionLink(techName, "Details","Home", new { TopicID = item.TechID },null) // Here I would like to encrypt the TopicID
<br />
<br />
#Html.DisplayFor(modelItem => item.TechDesc)
}
Here are a couple of simple methods you can use to encode/decode.
The encoded value is not secure, and as you can see, decoding it is trivial. If your goal is to obfuscate the id, this will work. If you need to secure it, you should take a different approach.
public string Encode( string encodeMe )
{
byte[] encoded = System.Text.Encoding.UTF8.GetBytes( encodeMe );
return Convert.ToBase64String( encoded );
}
public static string Decode( string decodeMe )
{
byte[] encoded = Convert.FromBase64String( decodeMe );
return System.Text.Encoding.UTF8.GetString( encoded );
}
So you could place these methods in your controller, and pass the encoded TechId to the view with viewBag
int techId = 1;
var encoded = Encode(id.ToString());
ViewBag.Encoded = encoded;
And then to use it in your link
#Html.ActionLink(techName, "Details","Home", new { TopicID = ViewBag.Encoded },null)
(Though, you should really consider using a view model. ViewBag, while a convienent and easy way to pass data to the view, is not considered to be best practice. Becoming comfortable with view models and strongly typed views will make your mvc life much easier in the future. Not to mention, produce cleaner and more maintainable code for those that follow you.)
Add A Folder with two classes
Class 1 : EncryptedActionParameterAttribute
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
namespace MVCInvoicClient.Extensions
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class EncryptedActionParameterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Dictionary<string, object> decryptedParameters = new Dictionary<string, object>();
if (HttpContext.Current.Request.QueryString.Get("q") != null)
{
string encryptedQueryString = HttpContext.Current.Request.QueryString.Get("q");
string decrptedString = Decrypt(encryptedQueryString.ToString());
string[] paramsArrs = decrptedString.Split('?');
for (int i = 0; i < paramsArrs.Length; i++)
{
string[] paramArr = paramsArrs[i].Split('=');
decryptedParameters.Add(paramArr[0], Convert.ToInt32(paramArr[1]));
}
}
for (int i = 0; i < decryptedParameters.Count; i++)
{
filterContext.ActionParameters[decryptedParameters.Keys.ElementAt(i)] = decryptedParameters.Values.ElementAt(i);
}
base.OnActionExecuting(filterContext);
}
private string Decrypt(string encryptedText)
{
string key = "jdsg432387#";
byte[] DecryptKey = { };
byte[] IV = { 55, 34, 87, 64, 87, 195, 54, 21 };
byte[] inputByte = new byte[encryptedText.Length];
DecryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByte = Convert.FromBase64String(encryptedText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(DecryptKey, IV), CryptoStreamMode.Write);
cs.Write(inputByte, 0, inputByte.Length);
cs.FlushFinalBlock();
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
}
}
Class 2 : MyExtensions
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MVCInvoicClient.Extensions
{
public static class MyExtensions
{
public static MvcHtmlString EncodedActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
{
string queryString = string.Empty;
string htmlAttributesString = string.Empty;
if (routeValues != null)
{
RouteValueDictionary d = new RouteValueDictionary(routeValues);
for (int i = 0; i < d.Keys.Count; i++)
{
if (i > 0)
{
queryString += "?";
}
queryString += d.Keys.ElementAt(i) + "=" + d.Values.ElementAt(i);
}
}
if (htmlAttributes != null)
{
RouteValueDictionary d = new RouteValueDictionary(htmlAttributes);
for (int i = 0; i < d.Keys.Count; i++)
{
htmlAttributesString += " " + d.Keys.ElementAt(i) + "=" + d.Values.ElementAt(i);
}
}
//What is Entity Framework??
StringBuilder ancor = new StringBuilder();
ancor.Append("<a ");
if (htmlAttributesString != string.Empty)
{
ancor.Append(htmlAttributesString);
}
ancor.Append(" href='");
if (controllerName != string.Empty)
{
ancor.Append("/" + controllerName);
}
if (actionName != "Index")
{
ancor.Append("/" + actionName);
}
if (queryString != string.Empty)
{
ancor.Append("?q=" + Encrypt(queryString));
}
ancor.Append("'");
ancor.Append(">");
ancor.Append(linkText);
ancor.Append("</a>");
return new MvcHtmlString(ancor.ToString());
}
private static string Encrypt(string plainText)
{
string key = "jdsg432387#";
byte[] EncryptKey = { };
byte[] IV = { 55, 34, 87, 64, 87, 195, 54, 21 };
EncryptKey = System.Text.Encoding.UTF8.GetBytes(key.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByte = Encoding.UTF8.GetBytes(plainText);
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(EncryptKey, IV), CryptoStreamMode.Write);
cStream.Write(inputByte, 0, inputByte.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
}
}
Controller
Add this line above the controller class Example for your Index
[EncryptedActionParameter]
In your View
#Html.EncodedActionLink("Download Invoice", "FileDownload","DataFiles", new { id = item.DataFilesID }, null)
add a using statement
#using MVCInvoicClient.Extensions
I came across this while looking for a secure method of doing this. In case someone else wishes to do this securely, you can use the MvcSerializer (I found it in the MVC futures 3 project, I am unsure whether it is included in MVC 4). For example:
(new MvcSerializer()).Serialize(<Your data here>, SerializationMode.EncryptedAndSigned)
And then to reverse the process...
(new MvcSerializer()).Deserialize(<Serialized data here>, SerializationMode.EncryptedAndSigned)
This is great because without any extra effort it encrypts and signs the data. The futures project also includes some attributes to make this happen automatically during model binding.