Apply any kind of Updates on database immedieately C# - c#

I have this program where I want to create a button base from Products on my database(ProductTbl). I found a way to do that
Here's the code:
public void DynamicButton() //Function for retrieving record and creating a button for each product
{
string select = "select ProductID,ProductDesc,ProductPrice,ProductPic from ProductTbl" ;
sda = new SqlDataAdapter(select,sqlConn);
sda.Fill(dataTable);
for (int i = 0; i < dataTable.Rows.Count; i++)
{
ExtendedButton prodBtn = new ExtendedButton(); //with ExtendedButton this time
prodBtn._itemName = dataTable.Rows[i][1].ToString();//this asigns the product name to the extended button
prodBtn._itemID = Convert.ToInt32(dataTable.Rows[i][0]);
prodBtn._myPrice = Convert.ToDecimal(dataTable.Rows[i][2]);
prodBtn.BackgroundImageLayout = ImageLayout.Stretch;
prodBtn.Click += new EventHandler(OnButtonClick);
prodBtn.Height = 100;
prodBtn.Width = 100;
System.Drawing.Font f1 = SystemFonts.DefaultFont;
prodBtn.Font = new System.Drawing.Font(f1.FontFamily,f1.Size,FontStyle.Bold);
prodBtn.Text = dataTable.Rows[i][1].ToString();
prodBtn.TextAlign = ContentAlignment.BottomCenter;
prodBtn.ForeColor = Color.White;
prodBtn.BackgroundImageLayout = ImageLayout.Zoom;
toolTip1.Show(prodBtn.Text, prodBtn);
byte[] image = (byte[])dataTable.Rows[i][3];
prodBtn.BackgroundImage = imgConverter.byteArrayToImage(image);
prodBtn.TextAlign = ContentAlignment.MiddleCenter;
flowPanel.Controls.Add(prodBtn);
}
}
//You can see this at codeproject
Now the problem is that whenever i add a product on that table using Stored procedure. I don't know how i can sync updates to the datatable that I use with this one. Any ideas and suggestion will be highly appreciated. Thanks sorry for the long post

You can use ASP.Net Caching with SqlCacheDependency.
See this page for details:
https://msdn.microsoft.com/en-us/library/ms178604.aspx

Related

Insert parent-child rows using Parallel programming

I have a method that iterates the rows using for loop and inside that for loop call the DNN API that inserts a parent child row into the database. The maximum to insert the data is 1000 rows per execution. I tested it on my local machine the performance is very slow. I am thinking to use a Parallel Programming, but not sure on how to implement this since there is a dependency on data insertion because of parent child relationship. And I am not sure if this is a good approach to use Parallel programming. Any help please?
Sample code
private void AddTab()
{
for (i = 0; i < 1000; i++) {
TabController tabController = new TabController();
var portalSettings = new
DotNetNuke.Entities.Portals.PortalSettings(info.PortalId);
TabInfo tab = new TabInfo();
tab.PortalID = info.PortalId;
tab.TabName = info.TabName;
tab.Title = info.Title;
tab.Description = info.TabName;
tab.KeyWords = info.TabName;
tab.IsVisible = info.IsVisible;
tab.DisableLink = info.IsDisabled;
tab.ParentId = info.ParentId == null ? Null.NullInteger : info.ParentId.GetValueOrDefault();
tab.IsDeleted = false;
tab.Url = "";
tab.SkinSrc = "[G]Skins/HRT.Portal.DNNThemes.Default/Home.ascx";
tab.ContainerSrc = portalSettings.DefaultPortalContainer;
tab.IsSuperTab = false;
var parentPage = tabController.GetTab(portalSettings.HomeTabId, info.PortalId);
//clone parent page permissions
foreach (TabPermissionInfo permission in parentPage.TabPermissions.ToList())
{
tab.TabPermissions.Add(permission);
}
int tabId = tabController.AddTab(tab, true);
}
}

Error adding usercontrol to windows form c#

I create a FaceDetectionEvent which is a user control and try to add it in windows form (still in the same project). But it keeps showing this error:
This is the FaceDetectionEvent code:
public partial class FaceDetectionEvent : UserControl
{
private System.Timers.Timer tListener;
private MySQL_DataAccess da = new MySQL_DataAccess();
private int iCurrentStatusIndex_ = 0;
private List<DataRow> lstFaceDetectionEvent = new List<DataRow>(20);
private ImageList cropImageList = new ImageList();
public FaceDetectionEvent()
{
InitializeComponent();
CreateColumns();
GetLastTwentyEvent();
tListener = new System.Timers.Timer(1000);
tListener.Elapsed += new System.Timers.ElapsedEventHandler(tListener_Elapsed);
tListener.Start();
}
public void GetLastTwentyEvent()
{
string strSQL = string.Format("SELECT * FROM av_status_log AS A LEFT JOIN avmediaserver AS B ON A.device_id=B.DeviceId "
+ "LEFT JOIN privilege_device AS C ON A.device_id = C.device_id "
+ "LEFT JOIN privilege_device_group AS D ON C.device_group_id = D.device_group_id "
+ "WHERE event_type_id = 8 ORDER BY A.db_time DESC LIMIT 20");
DataTable dt = da.GetInfoData(strSQL).Tables[0];
if (dt.Rows.Count > 0)
iCurrentStatusIndex_ = Convert.ToInt32(dt.Rows[0]["rowid"]);
foreach (DataRow dr in dt.Rows)
{
lstFaceDetectionEvent.Add(dr);
string strCroppedImage = GetCropImageBase64String(dr["memo"].ToString());
cropImageList.Images.Add(Base64ToImage(strCroppedImage));
}
ShowFDEvent();
}
void tListener_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
string strSQL = string.Format("SELECT * FROM av_status_log AS A LEFT JOIN avmediaserver AS B ON A.device_id=B.DeviceId "
+ "LEFT JOIN privilege_device AS C ON A.device_id = C.device_id "
+ "LEFT JOIN privilege_device_group AS D ON C.device_group_id = D.device_group_id "
+ "WHERE A.rowid > {0} AND event_type_id = 8 ORDER BY A.db_time DESC", iCurrentStatusIndex_.ToString());
DataTable dt = da.GetInfoData(strSQL).Tables[0];
if (dt.Rows.Count > 0)
iCurrentStatusIndex_ = Convert.ToInt32(dt.Rows[0]["rowid"]);
if (lstFaceDetectionEvent.Count >= 20)
{
lstFaceDetectionEvent.RemoveRange(0, dt.Rows.Count);
for (int i = 0; i < dt.Rows.Count; i++)
{
cropImageList.Images.RemoveAt(i);
}
}
foreach (DataRow dr in dt.Rows)
{
lstFaceDetectionEvent.Add(dr);
string strCroppedImage = GetCropImageBase64String(dr["memo"].ToString());
cropImageList.Images.Add(Base64ToImage(strCroppedImage));
}
ShowFDEvent();
this.Refresh();
}
public string GetCropImageBase64String(string pStrMemo)
{
XElement doc = XElement.Parse(pStrMemo);
string strCropImage = doc.Element("cropImage").Value;
return strCropImage;
}
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
private void CreateColumns()
{
ColumnHeader cropImageHeader = new ColumnHeader();
cropImageHeader.Text = "Crop Image";
cropImageHeader.Width = 150;
FDEventlistView.Columns.Add(cropImageHeader);
ColumnHeader timestampHeader = new ColumnHeader("Event Time");
timestampHeader.Text = "Event Time";
timestampHeader.Width = 150;
FDEventlistView.Columns.Add(timestampHeader);
ColumnHeader deviceNameHeader = new ColumnHeader("Device Name");
deviceNameHeader.Text = "Size";
deviceNameHeader.Width = 80;
FDEventlistView.Columns.Add(deviceNameHeader);
}
private void ShowFDEvent()
{
FDEventlistView.Items.Clear();
FDEventlistView.BeginUpdate();
int i = 0;
foreach (DataRow dr in lstFaceDetectionEvent)
{
ListViewItem item = new ListViewItem();
item.ImageIndex = i;
ListViewItem.ListViewSubItem subitem = new ListViewItem.ListViewSubItem();
subitem.Text = dr["status_time"].ToString();
item.SubItems.Add(subitem);
subitem = new ListViewItem.ListViewSubItem();
subitem.Text = dr["device_name"].ToString();
item.SubItems.Add(subitem);
FDEventlistView.Items.Add(item);
i++;
}
FDEventlistView.EndUpdate();
}
}
Do you have any idea why?
Code in your UserControl will run at design time as well. A feature that provides the WYSIWIG behavior of a control when you drop it on a form with the designer. But certainly can be troublesome, in this case you do not want to query the dbase, no chance that you'll be able to find the correct connection string when the control is loaded in Visual Studio instead of your program. Simply skipped by using the DesignMode property:
public FaceDetectionEvent()
{
InitializeComponent();
tListener = new System.Timers.Timer(1000);
tListener.Elapsed += new System.Timers.ElapsedEventHandler(tListener_Elapsed);
if (!this.DesignMode) {
CreateColumns();
GetLastTwentyEvent();
tListener.Start();
}
}
You may need to insert the DesignMode test in other places in your code, like Paint and Load event handlers.
Do note how debugging such design-time only exceptions can be difficult, the message box isn't big enough to show you the stack trace. In the really hard cases you may need to debug Visual Studio itself so you can see the exception. Start another instance of VS and use Tools + Attach to Process to attach the debugger to the 1st instance. Debug + Exceptions, tick the Thrown checkbox to automatically break when the exception is thrown.
I don't think the problem is about UserControl. To prove this, create a new user control, this time not programmatically -> Add New and choose UserControl. Delete the FaceDetectionEvent Control from the MainForm for now, then add the newly created UserControl and see if the error shows up again. If it does please share the content of the StackTrace.
I've had this same issue trying to add my user controls to a form by dragging it from the tool box. It may seem obvious, but my issues involved having parameters in the constructor that were intended to be passed at run-time if the control was added programatically...
So this code will cause the error. To avoid it don't have arguments in the constructor.
public ucMyControl(string title)
{
InitializeComponent();
groupBox1.Text = title;
}

Not getting BarChart in Winform Application

I am trying to show a dynamic barchart from database in winform application but it is not coming and giving me Argument out of Exception error at var p2 = series.Points[arrlocationSTD]; when arrlocationSTD=1. Here is my code in c#..
void LoadBarChart(string qurystring)
{
if (calltype.Equals("TRANSFERED"))
{
totalTransfered = dr["SummaryOfCalls"].ToString();
intTRANSFERED = int.Parse(totalTransfered, CultureInfo.InvariantCulture);
if (i == 0)
{
arrlocationTransferred = i;
series.Points.Add(intTRANSFERED);
var p7 = series.Points[arrlocationTransferred];
p7.Color = Color.Yellow;
p7.AxisLabel = "TRANSFERED";
p7.LegendText = "TRANSFERED";
p7.Label = totalTransfered;
i++;
}
else
{
arrlocationTransferred = i;
series.Points.Add(intTRANSFERED);
var p7 = series.Points[arrlocationTransferred];
p7.Color = Color.Yellow;
p7.AxisLabel = "TRANSFERED";
p7.LegendText = "TRANSFERED";
p7.Label = totalTransfered;
}
}
}
barChart.Invalidate();
pnlBar.Controls.Add(barChart);
}
Please help me to resolve this.
Thanks in advance..
You'll need to add your additional processing, but the following might help.
I'd strongly recommend that you get the chart showing your data correctly before you start changing colour properties and such.
void LoadBarChart(string qurystring)
{
String conn = Strings.ConnectionString; // You fill this in.
Dictionary<String,int> callSummariesByTypeOfCall =
new Dictionary<String,int>();
MySqlConnection con = new MySqlConnection(conn);
MySqlCommand comm = new MySqlCommand(qurystring, con);
con.Open();
MySqlDataReader dr = comm.ExecuteReader();
// Get the data into a dictionary
while (dr.Read())
{
String calltype = dr["TypeOfCall"].ToString();
int summary = int.Parse(dr["Calls"].ToString(), CultureInfo.InvariantCulture);
callSummariesByTypeOfCall[calltype] = summary;
}
// Do any other processing you need here
// Bind the data onto the Series
Series series = new Series
{
Name = "series2",
IsVisibleInLegend = false,
ChartType = SeriesChartType.Column
};
series.Points.DataBindXY(
callSummariesByTypeOfCall.Keys,
callSummariesByTypeOfCall.Values);
barChart.Series.Add(series);
barChart.Invalidate();
pnlBar.Controls.Add(barChart);
}

Unable to show two or more data rows in the gridview when binding with the List

When the add button is clicked second time, there is supposed to be two lines of data rows in the GridView ( the first row is the first click and the second row is the newly added data). However there is only one data row.
List<DonationReceivedItem> drList = new List<DonationReceivedItem>();
protected void lbnAdd_Click(object sender, EventArgs e)
{
DonationReceivedItem temp = new DonationReceivedItem();
temp.donation = dID;
temp.productVariant = gvSelectVairant.SelectedRow.Cells[1].Text;
temp.productQuantity = tbQuantity.Text;
temp.isDistributed = "0";
drList.Add(temp);
gvNonExpired.DataSource = drList;
gvNonExpired.DataBind();
}
Try changing the following code:
DonationReceivedItem temp = new DonationReceivedItem();
temp.donation = dID;
temp.productVariant = gvSelectVairant.SelectedRow.Cells[1].Text;
temp.productQuantity = tbQuantity.Text;
temp.isDistributed = "0";
drList.Add(temp);
gvNonExpired.DataSource = drList;
gvNonExpired.DataBind();
to:
DonationReceivedItem temp = new DonationReceivedItem();
drList = gvNonExpired.DataSource;
temp.donation = dID;
temp.productVariant = gvSelectVairant.SelectedRow.Cells[1].Text;
temp.productQuantity = tbQuantity.Text;
temp.isDistributed = "0";
drList.Add(temp);
gvNonExpired.DataSource = drList;
gvNonExpired.DataBind();
See if that makes a difference :)
Because you are creating a new list you are wiping the previous data. First instantiate the list with the old data, then add the new data.

AutoComplete with context key in a Textbox based on two parameters?

Refer the Image, having 2 TextBox(tbxAttribute and tbxAttributeDesc).
Value will be loaded when page is loaded in tbxAttribute TextBox.In tbxAttributeDesc TextBox the end user will Fill that Data.
I have already Completed the Autocomplete Text in tbxAttributeDesc.
We are maintaining these Values in a table, Based up on the loaded tbxAttribute value their corresponding AttributeDesc will be highlight into tbxAttributeDesc Textbox
My Code be:
autoDesc = new AjaxControlToolkit.AutoCompleteExtender();
autoDesc.ID = "autoDesc" + i;
autoDesc.BehaviorID = "tbxAtribute" + i;
autoDesc.ServicePath = "itemvaluemas.asmx";
autoDesc.ServiceMethod = "GetAttributeDesc";
autoDesc.TargetControlID = tbxAttributeDesc.ID;
autoDesc.MinimumPrefixLength = 1;
autoDesc.CompletionInterval = 10;
autoDesc.FirstRowSelected = true;
autoDesc.CompletionSetCount = 30;
autoDesc.UseContextKey = true;
and also used Javscript Concept.
Refer the Below Image:
Here i need to pass condition as tbxAtribute and their Corresponding tbxAtributeDesc, based up on that tbxAbbr Value need to be highlight..
if i use ContextKey then how i pass these two textbox value in a context key..
If you have any idea please help to solve this problem.
Use ContextKey property to pass the value of textbox into GetAutoCompleteValues function.
txtbox1.Attributes.Add("onchange", "$find('BehaviourIDOftbxAttributeDesc').set_contextKey(tbxAttribute.value);");
For more information check the below links:
AJAX C# AutoCompleteExtender contextKey
http://arrao4u.wordpress.com/2010/01/14/autocomplete-extender-with-context-key/
This is the Solution which i found.
I use JavaScript:
function SetContextAbbr(formatid, itemValue, behaveid) {
var autoComplete1 = $find(behaveid);
var target = autoComplete1.get_element();
var txtformatid = document.getElementById(formatid);
var txtitemValue = document.getElementById(itemValue);
var contextkeydata = txtformatid.value + "-" + txtitemValue.value;
autoComplete1.set_contextKey(contextkeydata);
}
Use Function as
public string[] GetItemabbr(string prefixText, int count, string contextKey)
{
string[] splitvalue = contextKey.Split('-');
//code here
}
In WebService
autoabbr = new AjaxControlToolkit.AutoCompleteExtender();
autoabbr.ID = "autoabbr" + i;
autoabbr.BehaviorID = "autoabbrbehave" + i;
autoabbr.ServicePath ="itemvaluemas.asmx";
autoabbr.ServiceMethod = "GetItemabbr";
autoabbr.TargetControlID = txtItemAbbrValue.ID;
autoabbr.MinimumPrefixLength = 1;
autoabbr.CompletionInterval = 10;
autoabbr.FirstRowSelected = true;
autoabbr.CompletionListCssClass = "completionList";
autoabbr.CompletionListHighlightedItemCssClass = "itemHighlighted";
autoabbr.CompletionListItemCssClass = "listItem";
autoabbr.CompletionSetCount = 30;
autoabbr.UseContextKey = true;

Categories

Resources