C#

94K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

Share tech news, updates, or what's on your mind.

Sign up to Post

How can I suppress an empty line within a tablix cell?

In one cell I have different Field: Number, Description, Comment, Age
Sometimes alle fields are emtpy, maybe only one field is empty oder all can be filled.

I used the CanShrink Property for the row, but this doesn't have an effect.

And if I use: =IIF(String.IsNullOrEmpty(Fields!Comment.Value), True, False) then I see true or false.

So what do I have to do that if one of these field is empty or 0, the empty line is suppressed??

Kind regards, Marc
0
Hi,

I could use some help with a very mysterious error I am encountering. I am working with a windows application (.NET Framework 3.5, x86 platform, IDE = Visual Studio 2008, WPF frontend, MS Access backend, Jet OLEDB db connection) that, among other things, allows the user to generate plain text files and save them to a location of their choosing. The InvokeSaveDialog() function shown below is the piece that's giving me trouble.  

    
public class SaveFileDialogManager
    {
        public SaveFileDialogManager()
        {
            // CONSTRUCTOR
        }

        /// <summary>
        /// Prompts the user for the name of the file they intend to save.
        /// </summary>
        /// <param name="fileExt">File extension of file being saved</param>
        /// <param name="fileTypeDesc">Description of type of file being saved (ie. "SAS program")</param>
        /// <returns></returns>
        public static string InvokeSaveDialog(string fileExt, string fileTypeDesc)
        {
            // Create new SaveFileDialog object
            SaveFileDialog DialogSave = new SaveFileDialog();

            // Default file extension
            DialogSave.DefaultExt = fileExt;

            // Available file extensions
            DialogSave.Filter = fileTypeDesc + " (*." + fileExt + ")|*." + fileExt + "|All files (*.*)|*.*";
            // Adds a extension if the user does not
            DialogSave.AddExtension = true;

            // Restores the selected 

Open in new window

0
I have a number of old word documents that I need to migrate to pdf but first I need to save them as DOCX but I want to save them without the Encryption password (which I have).

Anybody know how to do this?
0
It shows the column without a button, but instead it shows the text "System.Windows.Control.Button"

<sdk:DataGrid x:Name="dgProjs" AutoGenerateColumns="False" HorizontalAlignment="Left" Height="271" Margin="4,40,0,0" Grid.RowSpan="1" VerticalAlignment="Top" Width="803"   Grid.Column="1"  SelectionChanged="dgProjs_SelectionChanged"  FontSize="9" AreRowDetailsFrozen="True" >
                <sdk:DataGrid.Columns>
                    <sdk:DataGridTemplateColumn Header=" ">
                        <sdk:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate >
                                <StackPanel Orientation="Vertical" VerticalAlignment="Center"  >
                                    <Button  />
                                </StackPanel>
                            </DataTemplate>
                        </sdk:DataGridTemplateColumn.CellTemplate>
                    </sdk:DataGridTemplateColumn>
                </sdk:DataGrid.Columns>
            </sdk:DataGrid>    
 
 
 
 
public ProjectView()
        {
            InitializeComponent();
            
            _objProjs = new ObservableCollection<ListOfProjs>();
            
            GetProjectsAndDisplay(rData, "");
 
        }
 
 
 
//   called web service to return rows from DB -  GetProjectsAndDisplay(rData, "");
 
void webService_GetProjectsTableCompleted(object sender, ServiceReference1.GetSqlResultTableCompletedEventArgs e)
        {
            string xmlResult = e.Result;

Open in new window

0
Hello Experts,
I am trying to debug a Stored Procedure and I get the following error as soon as I Start Debugging.  Any idea what is going on?

Error Message:  Unable to start T-SQL debugging. Could not attach to sql server process on XXX.  The object exporter specified was not found.

Thank you in advance!
0
I have a .net project with 2 layers: the Data layer (DAL) and the Business layer (BLL). I use Entity Framework - Database First in my DAL and I've implemented the Repository-Pattern in my BLL with the Get/GetById/Add/Update/Delete operations.

The reason that I use 2 layers and do not directly access the data layer is that must have business entities that can be manipulated as the data, but its may have some added logic that the data do not have.

for instance: in DAL I have 2 models (auto-generated by E.F.):
public partial class customer
{
    public int id { get; set; }
    public string firstname { get; set; }
    public string lastname { get; set; }

    public virtual ICollection<customers_addresses> customers_addresses { get; set; }
}

public partial class customers_addresses
{
    public int id { get; set; }
    public int customerId { get; set; }
    public string address1 { get; set; }
    public string address2 { get; set; }

    public virtual customer customer { get; set; }
}

Open in new window


In my BLL I have similar but not equal models (Check the differences in Camel Case and the Addresses property, and the pluralization of the name of the class customer_addresses)

public class Customer
{
    public int Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }

    public virtual ICollection<CustomerAddress> Addresses { get; set; }
}

public class CustomerAddress
{
    public int id { get; set; }
    public int CustomerId { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }

    public virtual Customer Customer { get; set; }
}

Open in new window


In my CustomerRepository I have the Get implementation:

/// <summary>
    /// Get All Customers
    /// </summary>
    /// <returns></returns>
    public IQueryable<Customer> Get()
    {
        var customers = _db.customers.Select(c => new Customer()
        {
            Id = c.id,
            Firstname = c.firstname,
            Lastname = c.lastname,
            Addresses = m.customers_addresses.Select(ca => new CustomerAddress()
            {
                Id = ca.id,
                CustomerId = ca.customerId,
                Address1 = ca.address1,
                Address2 = ca.address2
            })
        });

        return customers;
    }

Open in new window


These are my doubts and / or difficulties that I am having:

  • The Get operations in the repositories must be IQueryables and the Querys must be transferred to the Data entities (DAL) with their corresponding mapping (properties and navigation properties) in order to be able to filter them and select them as if they were the data
0
Hello,

how filter Datagridview rows using TextBox?


My code not work :/
 private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(textBox1.Text))
                    novetabdataBindingSource.Filter = string.Format("ID = '{0}'", textBox1.Text);
                else
                    novetabdataBindingSource.Filter = string.Empty;
             
            }
        }

Open in new window


edit
0
I have written code to load tree view in .net as below:

This code is executed to while the user expanding the a node.

 public void Populate_Node(Object sender, TreeNodeEventArgs e)
    {
        if (IsPostBack)
        {
          
            // Authenticating
            TreeProvider cmsTree = new TreeProvider(MembershipContext.AuthenticatedUser);
            //selecting the expanding node
            var node = cmsTree.SelectSingleNode(SiteContext.CurrentSiteName, "/Level1-2ndItem", "en-US");
            CMS.DocumentEngine.TreeNodeCollection myChildren = node.AllChildren;

            //Making array of child treenodes  of selected node
            IEnumerable<CMS.DocumentEngine.TreeNode> TreeNodes = myChildren.AsEnumerable<CMS.DocumentEngine.TreeNode>();
            foreach (var tree in myChildren)
            {
                System.Web.UI.WebControls.TreeNode ParenTreeNode = new System.Web.UI.WebControls.TreeNode();
                ParenTreeNode.Text = tree.NodeID.ToString() + ". " + SiteContext.CurrentSiteName;
                ParenTreeNode.Value = tree.NodeID.ToString();
                AddNodesExpand(ParenTreeNode);
                //AddNodesTillNthLevel(ParenTreeNode);                
            }
        }
    }

    private void AddExpandedNodes(System.Web.UI.WebControls.TreeNode TreeNode)
    {  
        CMS.DocumentEngine.TreeProvider cmsTree = new CMS.DocumentEngine.TreeProvider(CMS.Membership.MembershipContext.AuthenticatedUser);
        var node

Open in new window

0
Issue is that when I set a different it doesn't update neither my texblock.Text nor my listbox.Items;

Help very appreciated:)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Services.Maps;
using Windows.Devices.Geolocation;


// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace New_World_Map
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
       

     

        List<string> stringlist = new List<string>();

        public MainPage()
        {
            this.InitializeComponent();

            this.RightTapped += MainPage_RightTapped;

            mapscontrol.CenterChanged += Mapscontrol_CenterChanged;

            listbox.DoubleTapped += Listbox_DoubleTapped;

            listview.Items.Add("Zoom In");

            listview.Items.Add("Zoom Out");

            listview.Items.Add("Navigate North");

            listview.Items.Add("Navigate South");

 …
0
I would like the slider to change its value when the media is opened!:)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Storage;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace New_Video_Player
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        StorageLibrary publicvideoslibrary = null;

        StorageLibrary publicmusiclibrary = null;

        IStorageItem item = null;

        bool IsPaused = false;

        CheckBox pausecheckbox = null;

        CheckBox mutecheckbox = null;

        CheckBox loopcheckbox = null;

        StorageFolder f = null;

        bool IsChanged = false;

       

       

        public MainPage()
        {
            this.InitializeComponent();

            this.Loading += MainPage_Loading;

            this.RightTapped += MainPage_RightTapped;

           

            mediaelement.MediaOpened += …
0
I am getting an error message on my code. I am attempting to load a 0% and loading bar controlled by .progress with SceneManager.LoadSceneAsync. Here is my code: Thanks

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine.Events;
using UnityEngine.EventSystems;


public class  testLoading: MonoBehaviour
{

      public Image LoadingBar;
      public GameObject spaceToCont;
      private AsyncOperation async;
      public GameObject text;
      private int loadProgress = 0;


      IEnumerator Start (string level){

            {
            
                  yield return new WaitForSeconds (0.1f);
                  async = SceneManager.LoadSceneAsync ("jltvScene");
                  async.allowSceneActivation = false;

            }
            }

      void Update()

            {
                  LoadingBar.fillAmount = async.progress;

                  if (LoadingBar.fillAmount == 0.9f) {
                        spaceToCont.SetActive (true);
                        LoadingBar.fillAmount = 1f;
                  }
                  {
                        while (!async.isDone) {
                              loadProgress = (int)(async.progress * 100);
                              text.GetComponent<Text> ().text = "Loading Progress" + loadProgress + "%";
                              yield return null;
                        }
                  }
                  {
                        if (Input.GetKeyDown (KeyCode.Space)) {
                              Debug.Log ("Press Space To Continue");
                              async.allowSceneActivation = true;
                        }
                  }
            }
}
0
Display images dynamic in a Report.rdlc??


In our application I Have One Checkbox
 when I am selected Checkbox(checkbox in  billset form) Then Show image in Report.rdlc Form Printout
And
when I am  uncheck box Then Hide image in Report.rdlc Form  Printout

New to RDLC ...please give any suggestions.
0
Hi

We have Windows based Product developed using .Net, C#, SQL Server, Crystal reports etc.

We are using Infragistics Ultragrid for displaying data.   There are some screens which are used to insert / update data selected from main Ultragrid. When Insert / update through these screen is done, we are refreshing (fetching data from database and rebinding dataset) ultragrid regardless of whether one row inserted / updated, which is quite a performance hit

I want to change this real time update i.e. if out of 1000 rows, if I am selecting only 2-3 rows and performing operations on this set, once the operations are completed , instead of refreshing entire grid, I want to update (refresh) only affected grid rows.  In addition I am thinking of using LOCKS to maintain concurrency


What is the best possible way to achieve this?  I don't want to use SQLReader. We are not using connected architecture. We are using ADO.Net (disconnected mode)

Your suggestions are much appreciated.

thanks in advance
0
Hi ,

I am using masterpage and masterpage is having Ajax ModalPopupExtender Control. Also page uses Frames. ModalPopup shows always in the top frame and top frame is greyed out. Bottom frame is not greyed out. how to to show modalpopup window in the center of the page and both frames are greyed out.

Masterpage.aspx
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="AdminMasterPage.master.cs" Inherits="CoreTeamFeedback.Administration.MasterPage" %>
<%@ 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">

   <asp:ContentPlaceHolder id="head" runat="server">
   </asp:ContentPlaceHolder>
<style>
 .modalBackground

    {
        background-color: #cccccc;
        filter: alpha(opacity=50);
        opacity: 0.6;
    }

    .modalPopup
    {
        background-color: #FFFFFF;
        width: 300px;
        border: 3px solid #507F70;
        border-radius: 12px;
        padding:0
    }

    .modalPopup .header
    {
        background-color: #285C4D;
        height: 30px;
        color: White;
        line-height: 30px;
        text-align: center;
        font-weight: bold;
        border-top-left-radius: 6px;
        border-top-right-radius: 6px;
        font-family:Verdana;
        font-size:8pt;
    }

    .modalPopup .body
    {
  

Open in new window

0
public void PostImagesToServer(Stream Images)
        {
         
            try
            {
                Guid Unique = System.Guid.NewGuid();
                string U = Unique.ToString();
                string Name = U + ".jpg";
                FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://NikhelPrans117@182.50.151.43/webservice/ChachaChaudaryImages/ComicImages/" + Name);
                req.Credentials = new NetworkCredential("NikhelPrans117", "Nilesh@2188");
                req.KeepAlive = true;
                req.UseBinary = true;
                req.Method = WebRequestMethods.Ftp.UploadFile;
                byte[] fileData = StreamToByte(Images);
                req.ContentLength = fileData.Length;
                Stream reqStream = req.GetRequestStream();
               
                reqStream.Write(fileData, 0, fileData.Length);
               
                reqStream.Close();
}
0
Hi all,

I would like to convert a List<string[]> into a multidimensional array string[,] through Linq (C#).

Which is the best solution?
0
Hi,
I'm running a script on Unity to run multiple applications at the same time with different settings the problem is every time I try to run the .sh file it gives me an error : Player data archive not found at 'location', using local filesystem. I looked up on google but no one seems to have the answer to this problem, do you have any idea why this is hapenning?

Thank you!

Log file attached.
global_index.js
index.js
0
Hi,

I have a string which I want to download as "xyz.txt" file using memorystream. I dont want to give any path.  The code is in c#. I tried below but gives nullreference exception at line :
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;


Below is the code

private void stringtostream()
{
      string streamout = string.Empty;
                using (MemoryStream ms = new MemoryStream())
                {
                    streamout ="..............................";
                    StreamWriter sw = new StreamWriter(ms);
                    sw.WriteLine(streamout);
                    sw.Flush();

                    byte[] buffer = ms.ToArray();

                    Download(buffer, "xyz.txt");
                }

}

private void Download(byte[] buffer, string fileName)
        {
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
           
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            string fileExtension = "txt";

            response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));

            response.OutputStream.Write(buffer, 0, buffer.Length);

            response.Flush();
            response.End();
        }
0
Hi Team,


We are trying to run the .rdlc report  using c# code in asp.net using reportviewer control in aspx page.


And when we run this website on prod server we are getting following error:


****************************************************************************************************************


Exception in page load eventand exception is
---Microsoft.Reporting.WebForms.LocalProcessingException: An error occurred
during local report processing. --->
Microsoft.Reporting.DefinitionInvalidException: The definition of the report
'Test-Consolidate.rdlc'
is invalid. --->
Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: An
unexpected error occurred in Report Processing. --->
System.IO.FileNotFoundException: Could not load file or assembly
'Microsoft.ReportViewer.ProcessingObjectModel, Version=10.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The
system cannot find the file specified. at
Microsoft.ReportingServices.RdlExpressions.ExprHostCompiler.InternalCompile(Report
report, AppDomain compilationTempAppDomain, Boolean refusePermissions) at
Microsoft.ReportingServices.RdlExpressions.ExprHostCompiler.<>c__DisplayClass1.b__0()
at
Microsoft.ReportingServices.Diagnostics.RevertImpersonationContext.<>c__DisplayClass1.b__0(Object
state) at System.Security.SecurityContext.Run(SecurityContext securityContext,
ContextCallback callback, Object state) at …
0
I programmatically created a Site Collection.  The parent site has Nintex and the created site collection shows the feature which I can then go and manually activate.

I need to do the same activation programmatically.  I found this piece of code and with small modification have tried it.  It runs, but when I check the site feature, Nintex workflows have not been activated.

The code follows:
        static void ActivateFeature(string FeatureGUID, string SiteURLToActivete)
        {
            SPSite oSPSite = new SPSite(SiteURLToActivete);

            //Get the Feature to Activate
            Microsoft.SharePoint.Administration.SPFarm farm = oSPSite.WebApplication.Farm;

            Microsoft.SharePoint.Administration.SPFeatureDefinitionCollection features = farm.FeatureDefinitions;

            //Nintex Worflow Feature GUID: ​0561d315-d5db-4736-929e-26da142812c5

            Microsoft.SharePoint.Administration.SPFeatureDefinition feature = features[new Guid(FeatureGUID)];

            if (feature != null)    //Make sure Feature is installed!
            {
                // Activate the feature
                oSPSite.Features.Add(feature.Id, true);
                //call oSPSite.Features.Remove
            }
        }

Open in new window

0
I am working on wpf application & calling web api for login verification -
 HttpClient client = new HttpClient();

            client.BaseAddress = new Uri("http://test.cloud.net/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            StringContent content = new StringContent(JsonConvert.SerializeObject(this.userObject), Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync("api/users/check", content);
            if (response.IsSuccessStatusCode)
            {
                MessageBox.Show(" Success");
            }
            else
                MessageBox.Show("Error Code" + response.StatusCode + " : Message - " + response.ReasonPhrase);

Open in new window


I am getting response code as 200 ok  success code as true. I want to read the data from json format . Can anyone please tell me how to read the response data.?
0
using log4net v1.2.10

How do I view the configuration that is created when I create the logger in C# code?

I am using code that dynamically adds appenders - so what I would like to do is view the config that was created after I activate the option and call BasicConfigurator.Configure().

Thanks in advance for your help!
0
Hi Experts:

I have following Financial Data:

ContractID  Center    Amount  Remarks
123         Center1   45  
456         Center2   67  
#           Center3   43  
            Center4   56      ContractID is blank
343         Center5   87

Open in new window

     

AS IS:

var query = ElasticsearchQueryBuilder<FinancialData>.Instance;  (OR IQueryBuilder<FinancialData> query)


 
var paramterValues = new List<string[]>()
{
    contractsList.ToArray(),   //contractsList is a var and have following ContractId  e.g. "123", "345", "#", ""
    CenterList.ToArray()       //CenterList is a var and have following values e.g. "Center1", "Center2" , "Center3", "Center4"
};

query.[b]Or[/b]<FinancialData>(paramterValues, x => x.ContractId, x => x.CenterNumber);

//This make a query to filter Financial data based on OR condition from ContractId or CenterNumber

Open in new window


To Be:

Condition1: I want to fetch only those records where ContractID should match  
Condition2: Center should match from CenterList data.
Condition3: ContractID should be # or blank only.

in other words  (Condition1) OR (Condition2 and Condition3)

Please help me in making this condition in c#
0
Hi,
I have one version of C# that works and reads negative numbers
correctly.

The serial communicator changed in another version of the same
C# project, supposedly faster processing.

The only difference I can see is tilde characters in the working version
missing from the broken version (screenshots attached).

What can be done to the serial communicator so it reads negative
numbers?

Thanks,
Priya
Broken.png
Working.png
0
I have a DataGridView in which there are 4 columns; Reference,Quantity, Rate and Amount.
The DataGridView is Editable. When I enter a value in the Reference Column then immediately it will fill the other values in the others cells from mysql database.
This is what I tried....
private void TAB_Credit_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

            try
            {
                if (TAB_Credit.CurrentCell.ColumnIndex == 0)
                {

                    MySqlDataAdapter sa = new MySqlDataAdapter("SELECT * FROM table WHERE Reference='" + TAB_Credit.Rows[e.RowIndex].Cells["Reference"].Value + "'", MyConnexion);
                    DataTable dt2 = new DataTable();

                    sa.Fill(dt2);
                    
                        double value = (double)TAB_Credit.Rows[e.RowIndex].Cells["Quantite"].Value * (double)TAB_Credit.Rows[e.RowIndex].Cells["PU"].Value;

                        TAB_Credit.Rows[e.RowIndex].Cells["Designation"].Value = dt2.Rows[0]["Designation"].ToString();
                        TAB_Credit.Rows[e.RowIndex].Cells["Quantite"].Value = dt2.Rows[0]["Quantite"].ToString();
                        TAB_Credit.Rows[e.RowIndex].Cells["PU"].Value = dt2.Rows[0]["Prix_Unitaire"].ToString();
                        TAB_Credit.Rows[e.RowIndex].Cells["Total"].Value = value.ToString();


                    }
                    
            }
            catch
            { }
        }

Open in new window

So in the datagrid,  when I insert in the Reference Cell nothing is appearing in the other cells.
Thank you.
0

C#

94K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).