LinqToSql query : deal with null values - sql-server

Here's a Linq-to-SQL query to check in a SQL Server view if 2 values are present: an integer (LOT) and a string (ART_CODE).
But sometimes those values are null in the view. In that case I get an exception showing up on screen.
How can I modify this code to deal with null values?
private void ValidProdPlusLotBtn_Click(object sender, RoutedEventArgs e)
{
int lot = Convert.ToInt32(NumLotTxtBox.Text);
string artCode = ArtCodeLB.Content.ToString();
try
{
#region Qte Restant à produire
DataClasses1DataContext dc2 = new DataClasses1DataContext();
var reste = from r in dc.Vw_MajPoids_Restant
where r.LOT == lot && r.ART_CODE == artCode
select new
{
r.PnetRestant,
r.NbuRestant
};
LotRestantTB.Text = reste.First().PnetRestant.ToString();
NbuRestantTB.Text = reste.First().NbuRestant.ToString();
#endregion
}
catch (Exception ex)
{
StackTrace st = new StackTrace();
Messages.ErrorMessages($"{st.GetFrame(1).GetMethod().Name}\n\n{ex.ToString()}");
}
}

I've found this which is working perfectly :
private void ValidProdPlusLotBtn_Click(object sender, RoutedEventArgs e)
{
int lot = Convert.ToInt32(NumLotTxtBox.Text);
string artCode = ArtCodeLB.Content.ToString();
try
{
#region Qte Restant à produire
DataClasses1DataContext dc2 = new DataClasses1DataContext();
var reste = from r in dc.Vw_MajPoids_Restant
where r.LOT == lot && r.ART_CODE == artCode
select new
{
r.PnetRestant,
r.NbuRestant
};
if(!reste.Any())
{
// Do nothing
}
else
{
LotRestantTB.Text = reste.First().PnetRestant.ToString();
NbuRestantTB.Text = reste.First().NbuRestant.ToString();
}
#endregion
}
catch (Exception ex)
{
StackTrace st = new StackTrace();
Messages.ErrorMessages($"{st.GetFrame(1).GetMethod().Name}\n\n{ex.ToString()}");
}
}
If it can help someone else...

Related

saving data at the Database SQLSERVER

I have a problem when I want to save the data in the database.
the exception is:
System.InvalidOperationException: 'DataColumn' Name_Faculty 'missing in DataTable' disconnGrid 'for SourceColumn' Name_Faculty '.'
public void fillGrid()
{
if (adoF2.ds.Tables["disconnGrid"] != null)
{
adoF2.ds.Tables["disconnGrid"].Clear(); // to get new update.
}
adoF2.da = new SqlDataAdapter("SELECT * FROM Students", adoF2.con1);
adoF2.da.Fill(adoF2.ds, "disconnGrid");
dataGridView1.DataSource = adoF2.ds.Tables["disconnGrid"];
}
public void fillCombo()
{
adoF2.da = new SqlDataAdapter("SELECT * FROM Faculty", adoF2.con1);
adoF2.da.Fill(adoF2.ds, "disconnCombo");
comboBox1.DataSource = adoF2.ds.Tables["disconnCombo"];
comboBox1.DisplayMember = adoF2.ds.Tables["disconnCombo"].Columns[1].ColumnName;
comboBox1.ValueMember = adoF2.ds.Tables["disconnCombo"].Columns[0].ColumnName; /* this column is a foreign key into 'Students' table*/
}
private void gestionStagiaire2_Load(object sender, EventArgs e)
{
fillGrid();
fillCombo();
}
// to add the new row in the dataTable[disconnGrid]
private void button1_Click(object sender, EventArgs e)
{
adoF2.row1 = adoF2.ds.Tables["disconnGrid"].NewRow();
adoF2.row1[0] = textID.Text;
adoF2.row1[1] = textName.Text;
adoF2.row1[2] = comboBox1.SelectedValue; // to get the value not what is diplayed on the UI of comboBox1.
for (int i = 0; i < adoF2.ds.Tables["disconnGrid"].Rows.Count; i++)
{
if (textID.Text == adoF2.ds.Tables["disconnGrid"].Rows[i].ToString())
{
MessageBox.Show("Sorry the students is existed", "Warning", MessageBoxButtons.OK);
return; // to avoid errors.
}
}
adoF2.ds.Tables["disconnGrid"].Rows.Add(adoF2.row1);
MessageBox.Show("The students has been added successfully", "info", MessageBoxButtons.OK,MessageBoxIcon.Information);
dataGridView1.DataSource = adoF2.ds.Tables["disconnGrid"]; // to get the newly update.
}
// to save the data into the database:
private void saveB_Click(object sender, EventArgs e)
{
adoF2.cmdbuilder = new SqlCommandBuilder(adoF2.da);
adoF2.da.Update(adoF2.ds.Tables["disconnGrid"]);
MessageBox.Show("Saving has been succeeded", "Info", MessageBoxButtons.OK);
}
try this code :
adoF2.cmdbuilder = new SqlCommandBuilder(adoF2.da);
adoF2.da.Update(adoF2.ds,"disconnGrid");
MessageBox.Show("Saving has been succeeded", "Info", MessageBoxButtons.OK);

While attaching current binding source error occurs: "An entity object cannot be referenced by multiple instances of IEntityChangeTracker"

I have created simple form for editing client list using Entity Framework and data binding. However, when im trying to edit rows error "An entity object cannot be referenced by multiple instances of IEntityChangeTracker" occurs. I don't know where I attach one object to two data contexts..
Main user control:
ArtGalleryEntities db;
public UserControl5()
{
InitializeComponent();
}
private void UserControl5_Load(object sender, EventArgs e)
{
db = new ArtGalleryEntities();
db.Configuration.LazyLoadingEnabled = false;
klienciBindingSource.DataSource = db.Klienci.ToList();
}
private void edit_button_Click(object sender, EventArgs e)
{
if (klienciBindingSource.Current == null)
return;
using (AddEditForm frm = new AddEditForm(klienciBindingSource.Current as Klienci))
{
if (frm.ShowDialog() == DialogResult.OK)
{
klienciBindingSource.DataSource = db.Klienci.ToList();
}
}
}
AddEditForm here :
ArtGalleryEntities db;
public AddEditForm(Klienci obj)
{
InitializeComponent();
db = new ArtGalleryEntities();
if (obj == null)
{
klienciBindingSource.DataSource = new Klienci();
db.Klienci.Add(klienciBindingSource.Current as Klienci);
}
else
{
db.Entry(obj).State = System.Data.Entity.EntityState.Unchanged;
klienciBindingSource.DataSource = obj;
db.Klienci.Attach(klienciBindingSource.Current as Klienci); // here error occurs
}
}
I have tried following replaces for attaching:
db.Entry(klienciBindingSource.Current as Klienci).State = System.Data.Entity.EntityState.Unchanged;
db.Entry(klienciBindingSource.Current as Klienci).State = System.Data.Entity.EntityState.Modified;
But it didn't work out for me

SqlCacheDepency.. QueryNotification subscription not working

public class MemoryCacheHelper
{
private static string _conn = ConfigurationManager.ConnectionStrings["EFMultiPoolDbContext"] != null ?
ConfigurationManager.ConnectionStrings["EFMultiPoolDbContext"].ConnectionString :
ConfigurationManager.ConnectionStrings["EFDbContext"].ConnectionString;
private static Logger _logger = LogManager.GetCurrentClassLogger();
private static int _hourOfExpiry = 8; // ConfigurationHelper.GetValue<int>("Cache:HourExpiry", 8);
//private static SqlDependency dependency;
private static ObjectCache _cache = MemoryCache.Default;
private static WebCaching.Cache _webcache = new WebCaching.Cache();
private ReaderWriterLockSlim _cachelock = null;
public MemoryCacheHelper()
{
_cachelock = new ReaderWriterLockSlim();
EnoughPermission();
}
public void Add(string key, object val)
{
Add(key, val, new CacheItemPolicy()
{
SlidingExpiration = new TimeSpan(_hourOfExpiry, 0, 0)
});
}
public void Add(string key, object val, int seconds)
{
Add(key, val, new CacheItemPolicy()
{
//SlidingExpiration = new TimeSpan(0,0,seconds)
AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(seconds))
});
}
public void Add(string key, object val, int mins, WebCaching.CacheDependency dependency)
{
if (val == null)
return;
//_cachelock.EnterReadLock();
try
{
//if (_cache1.Get(key) != null)
{
_logger.Debug(string.Format("Cache Key: {0} set at {1}", key, DateTime.Now));
_webcache.Insert(key, val, dependency, WebCaching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(mins),
WebCaching.CacheItemPriority.Default, CacheItemRemovedCallback);
//if (key == "productTypes")
// _logger.Debug(string.Format("Cache Key: {0} set at {1}", key, DateTime.Now));
}
}
finally
{
// _cachelock.ExitReadLock();
}
}
public static T CheckOrRequeryWebCache<T>(string key, int mins, string commandText)
{
var cache = new MemoryCacheHelper();
object res = cache.GetWebCacheItem(key);
if (res == null)
{
SqlDependency.Stop(_conn);
SqlDependency.Start(_conn);
using (var con = new SqlConnection(_conn))
{
using (var cmd = new SqlCommand())
{
con.Open();
cmd.Connection = con;
cmd.Notification = null;
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.CommandText=#"SET ANSI_NULLS ON;SET ANSI_PADDING ON;SET ANSI_WARNINGS ON;SET CONCAT_NULL_YIELDS_NULL ON;SET QUOTED_IDENTIFIER ON;SET NUMERIC_ROUNDABORT OFF;SET ARITHABORT ON;";
{
cmd.ExecuteNonQuery();
}
cmd.CommandText = commandText;
var ds = new DataSet();
da.Fill(ds);
if (key == "visualIdPLUs")
res = ds.Tables[0].AsEnumerable().Select(x => Convert.ToString(x["ParentPLU"])).ToList();
else
res = ds.Tables[0].AsEnumerable().Select(x => new BlockedGIdDateExchangePLU
{
PLU = Convert.ToString(x["ParentPLU"]),
CanExchangeDate = Convert.ToBoolean(x["CanExchangeDate"]),
CanExchangeGId = Convert.ToBoolean(x["CanExchangeGId"])
}).ToList();
var dependency = new WebCaching.SqlCacheDependency(cmd);
//dependency = new SqlDependency(cmd);
//dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
cache.Add(key, res, mins, dependency);
}
}
}
return (T)res;
}
private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
}
private bool EnoughPermission()
{
SqlClientPermission perm = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
try
{
perm.Demand();
return true;
}
catch (System.Exception)
{
return false;
}
}
}
profiler trace for working sample profiler trace for my main projectAm working on SqlCacheDependency. i need to implement it in my main project
in order to test first , i have created sample MVC project and implemented is working perfectly fine, can see all the QueryNotification events on profiler.
when am trying to run the same code in my main project is not working.. the problem i found out from sql profiler is not all qn events are firing.. starting from susbscription event.
can anyone please suggest what is wrong.. (note: am using same database and sql login for both sample and main project)

Microsoft.VisualStudio.Debugger.Runtime.Main.ThrowCrossThreadMessageException

I have created an Excel Add-In in Visual Studio 2008 for Excel 2003 that (among other things) clears object data from multiple excel sheets based on user selection. The add-in runs as it should, however, at random intervals on various actions will cause Excel to crash. The code below contains a windows form with a progress bar, background worker and open file dialog (ofd). This exception gets thrown: Microsoft.VisualStudio.Debugger.Runtime.Main.ThrowCrossThreadMessageException (in case it isn't obvious) during the Main() event at this.progressbar1.Text. I have tried several different methods to resolve this problem and it may be reflected in this code snippet - perhaps someone could enlighten me as to what I am doing wrong and what - if any of the methods that have been added - may be unnecessary.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32;
namespace WindowsFormApplication
{
public partial class Form3 : Form
{
private int highestPercentageReached = 0;
private bool skipreadonly = true;
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
Thread newThread = new Thread(new ThreadStart(main));
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
}
[STAThread]
private void main()
{
if ((bool)Invoke(new ExcelSelectHandler(ExcelSelect)))
{
Invoke(new MethodInvoker(this.Show));
backgroundWorker1.RunWorkerAsync();
}
else
{
Invoke(new MethodInvoker(this.Close));
}
}
private void Form3_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (Char)Keys.Escape)
{
backgroundWorker1.CancelAsync();
}
}
private delegate bool ExcelSelectHandler();
private bool ExcelSelect()
{
Invoke(new MethodInvoker(this.Hide));
ofd.Title = "Excel Reset";
ofd.Multiselect = true;
ofd.FileName = "";
ofd.Filter = "Excel Files|*.xls;*.xlsx;*.xlt;*.xltx;*.xlsb;*.xlsm;*.xltm";
DialogResult result = ofd.ShowDialog();
return result == DialogResult.OK;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
DataRemove(worker, e);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
MethodInvoker proginvoke = delegate
{
progressBar1.Value = e.ProgressPercentage;
};
progressBar1.BeginInvoke(proginvoke);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
Invoke(new MethodInvoker(this.Close));
}
else
{
Invoke(new MethodInvoker(this.Close));
}
}
private void DataRemove(BackgroundWorker worker, DoWorkEventArgs e)
{
try
{
object missing = System.Reflection.Missing.Value;
int k = ofd.FileNames.Length;
int l = 0;
Excel.Application eapp = ThisAddIn.xlApplication;
Excel.Workbook eawb = eapp.ActiveWorkbook;
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.ScreenUpdating = false;
xlApp.Visible = false;
Excel.Workbook xlWorkbook;
foreach (var filename in ofd.FileNames)
{
if (l < k)
{
if (filename != eawb.FullName)
{
xlWorkbook = xlApp.Workbooks.Open(ofd.FileNames[l].ToString(), missing, missing, missing, missing, missing, true, missing, missing, missing, true, missing, missing, missing, missing);
Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlApp.ActiveSheet;
Excel.ListRows xlRows = (Excel.ListRows)xlWorksheet.ListObjects;
if (xlWorkbook.ReadOnly)
{
if (skipreadonly)
{
xlWorkbook.Close(false, missing, missing);
}
else
{
Invoke(new MethodInvoker(this.Hide));
if (MessageBox.Show("Excel document '" + ofd.SafeFileNames[l].ToString() + "' is either opened or marked read only and data will not removed from this file. Do you want to ignore this file and continue removing data?", "Data Remover", MessageBoxButtons.YesNo) == DialogResult.No)
{
Invoke(new MethodInvoker(this.Show));
if (worker.WorkerSupportsCancellation == true)
{
worker.CancelAsync();
xlWorkbook.Close(false, missing, missing);
break;
}
}
else
{
Invoke(new MethodInvoker(this.Show));
xlWorkbook.Close(false, missing, missing);
}
}
}
else
{
if (xlRows.Count > 0)
{
foreach (Excel.ListRow xlRow in xlRows)
{
xlRow.Delete();
}
}
xlWorkbook.Save();
xlWorkbook.Close(true, missing, missing);
}
Marshal.ReleaseComObject(xlRows);
Marshal.ReleaseComObject(xlWorksheet);
Marshal.ReleaseComObject(xlWorkbook);
}
else
{
Excel.Worksheet exlWorksheet = (Excel.Worksheet)eawb.ActiveSheet;
Excel.ListRows xlRows = (Excel.ListRows)exlWorksheet.ListObjects;
foreach (Excel.ListRow xlRow in xlRows)
{
xlRow.Delete();
}
}
l += 1;
}
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
else
{
int percentComplete = l / k * 100;
highestPercentageReached = percentComplete;
worker.ReportProgress(percentComplete);
}
}
xlApp.Quit();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(xlApp);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}

Query CRM data in Silverlight

I am building a silverlight app for CRM 2011 and I was wondering what the best way to retrieve data from the CRM system is.
I have linked in my organisation as a service reference and am able to access that. I have seen a few different ways to retrieve data but they all seem rather complicated. Is there anything like what we can use in plugins such as a fetch XMl query or a simple Service.Retrieve method?
Thanks
If you add a service reference to your project you can use LINQ to query the datasets.
You can download the CSDL from Developer Resources under the customisation area.
private FelineSoftContext context;
private System.String serverUrl;
private DataServiceCollection<SalesOrder> _orders;
public MainPage()
{
InitializeComponent();
serverUrl = (String)GetContext().Invoke("getServerUrl");
//Remove the trailing forward slash returned by CRM Online
//So that it is always consistent with CRM On Premises
if (serverUrl.EndsWith("/"))
serverUrl = serverUrl.Substring(0, serverUrl.Length - 1);
Uri ODataUri = new Uri(serverUrl + "/xrmservices/2011/organizationdata.svc/", UriKind.Absolute);
context = new FelineSoftContext(ODataUri) { IgnoreMissingProperties = true };
var orders = from ord in context.SalesOrderSet
orderby ord.Name
select new SalesOrder
{
Name = ord.Name,
SalesOrderId = ord.SalesOrderId
};
_orders = new DataServiceCollection<SalesOrder>();
_orders.LoadCompleted += _orders_LoadCompleted;
_orders.LoadAsync(orders);
}
void _orders_LoadCompleted(object sender, LoadCompletedEventArgs e)
{
if (e.Error == null)
{
if (_orders.Continuation != null)
{
_orders.LoadNextPartialSetAsync();
}
else
{
OrderLookup.ItemsSource = _orders;
OrderLookup.DisplayMemberPath = "Name";
OrderLookup.SelectedValuePath = "Id";
}
}
}
You will also need to add a method in your class as below:
private static ScriptObject GetContext()
{
ScriptObject xrmProperty = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");
if (null == xrmProperty)
{
//It may be that the global context should be used
try
{
ScriptObject globalContext = (ScriptObject)HtmlPage.Window.Invoke("GetGlobalContext");
return globalContext;
}
catch (System.InvalidOperationException)
{
throw new InvalidOperationException("Property \"Xrm\" is null and the Global Context is not available.");
}
}
ScriptObject pageProperty = (ScriptObject)xrmProperty.GetProperty("Page");
if (null == pageProperty)
{
throw new InvalidOperationException("Property \"Xrm.Page\" is null");
}
ScriptObject contextProperty = (ScriptObject)pageProperty.GetProperty("context");
if (null == contextProperty)
{
throw new InvalidOperationException("Property \"Xrm.Page.context\" is null");
}
return contextProperty;
}
You will need to add an additional class library and put the following code within it. Change the class name to match the Context you exported:
partial class FelineSoftContext
{
#region Methods
partial void OnContextCreated()
{
this.ReadingEntity += this.OnReadingEntity;
this.WritingEntity += this.OnWritingEntity;
}
#endregion
#region Event Handlers
private void OnReadingEntity(object sender, ReadingWritingEntityEventArgs e)
{
ODataEntity entity = e.Entity as ODataEntity;
if (null == entity)
{
return;
}
entity.ClearChangedProperties();
}
private void OnWritingEntity(object sender, ReadingWritingEntityEventArgs e)
{
ODataEntity entity = e.Entity as ODataEntity;
if (null == entity)
{
return;
}
entity.RemoveUnchangedProperties(e.Data);
entity.ClearChangedProperties();
}
#endregion
}
public abstract class ODataEntity
{
private readonly Collection<string> ChangedProperties = new Collection<string>();
public ODataEntity()
{
EventInfo info = this.GetType().GetEvent("PropertyChanged");
if (null != info)
{
PropertyChangedEventHandler method = new PropertyChangedEventHandler(this.OnEntityPropertyChanged);
//Ensure that the method is not attached and reattach it
info.RemoveEventHandler(this, method);
info.AddEventHandler(this, method);
}
}
#region Methods
public void ClearChangedProperties()
{
this.ChangedProperties.Clear();
}
internal void RemoveUnchangedProperties(XElement element)
{
const string AtomNamespace = "http://www.w3.org/2005/Atom";
const string DataServicesNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices";
const string DataServicesMetadataNamespace = DataServicesNamespace + "/metadata";
if (null == element)
{
throw new ArgumentNullException("element");
}
List<XElement> properties = (from c in element.Elements(XName.Get("content", AtomNamespace)
).Elements(XName.Get("properties", DataServicesMetadataNamespace)).Elements()
select c).ToList();
foreach (XElement property in properties)
{
if (!this.ChangedProperties.Contains(property.Name.LocalName))
{
property.Remove();
}
}
}
private void OnEntityPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (!this.ChangedProperties.Contains(e.PropertyName))
{
this.ChangedProperties.Add(e.PropertyName);
}
}
#endregion
}
I am will suggest you to use Silvercrmsoap , it's very easy to use. I have used this in my silverlight projects.

Resources