Saturday, August 31, 2013

C# - Question about events (also textbox clearing and starting/stopping a timer)

You can do locking to prevent threads from stepping on each other



class ThreadSafe
{
static readonly object _locker = new object();
static int _val1, _val2;
static void Go()
{
lock (_locker)
{
if (_val2 != 0) Console.WriteLine (_val1 / _val2);
_val2 = 0;
}
}
}

Here is a way to communicate between threads.



class TwoWaySignaling
{
static EventWaitHandle _ready = new AutoResetEvent(false);
static EventWaitHandle _go = new AutoResetEvent(false);
static readonly object _locker = new object();
static string _message;
static void Main()
{
new Thread(Work).Start();
_ready.WaitOne(); // First wait until worker is ready
lock (_locker) _message = "ooo";
_go.Set(); // Tell worker to go
_ready.WaitOne();
lock (_locker) _message = "ahhh"; // Give the worker another message
_go.Set();
_ready.WaitOne();
lock (_locker) _message = null; // Signal the worker to exit
_go.Set();
}
static void Work()
{
while (true)
{
_ready.Set(); // Indicate that we're ready
_go.WaitOne(); // Wait to be kicked off...
lock (_locker)
{
if (_message == null) return; // Gracefully exit
Console.WriteLine(_message);
}
}
}
}


How do make the texbox accept only numerics, del key and backspace?

How do make the texbox accept only numerics, del key and backspace?


public partial class Form1 : Form
{
/// <summary>
/// Whether Del is pressed or not
/// </summary>
private bool isDelPressed = false;

public Form1()
{
InitializeComponent();
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
int n = (int)e.KeyChar;
e.Handled = !(n == 8 || (n >= 48 && n <= 57) || isDelPressed);
}

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
isDelPressed = (e.KeyCode == Keys.Delete);
}
}



If you think one reply solves your problem, please mark it as An Answer , if you think someone's reply helps you, please mark it as a Proposed Answer



Help by clicking:

Click here to donate your rice to the poor

Click to Donate

Click to feed Dogs & Cats




Found any spamming-senders? Please report at: Spam Report


How do make the texbox accept only numerics, del key and backspace?

I always prefer to do it via client side Javascript... It is faster than using code behind



<asp:TextBox ID="txtNumber" runat="server" onkeypress="AllowNumeric();" MaxLength="8"></asp:TextBox>

Choose the Javascript you prefer.



function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function AllowNumeric() {
if ((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode == 46) || (event.keyCode == 45)) {
event.returnValue = true;
}
else {
event.returnValue = false;
}
}


How do make the texbox accept only numerics, del key and backspace?

PaulDAndrea;)


Maybe the problem of Windows Form instead of Web Form;)




If you think one reply solves your problem, please mark it as An Answer , if you think someone's reply helps you, please mark it as a Proposed Answer



Help by clicking:

Click here to donate your rice to the poor

Click to Donate

Click to feed Dogs & Cats




Found any spamming-senders? Please report at: Spam Report


C# - Question about events (also textbox clearing and starting/stopping a timer)

Please use System.Windows.Form.Timer instead of the Timer you are referring, because the "Timer" of System.Timers.Timer is used Windows Service and it's based on thread, if you refer this directly, this will cause the problem of causing an error "A thread cannot access a control that isn't created by the thread itself".


Then in the Form_Load, please set the property——Enabled = true




If you think one reply solves your problem, please mark it as An Answer , if you think someone's reply helps you, please mark it as a Proposed Answer



Help by clicking:

Click here to donate your rice to the poor

Click to Donate

Click to feed Dogs & Cats




Found any spamming-senders? Please report at: Spam Report


C# - Question about events (also textbox clearing and starting/stopping a timer)

Can you submit your codes or sample code onto SyDrive for us to download to see?




If you think one reply solves your problem, please mark it as An Answer , if you think someone's reply helps you, please mark it as a Proposed Answer



Help by clicking:

Click here to donate your rice to the poor

Click to Donate

Click to feed Dogs & Cats




Found any spamming-senders? Please report at: Spam Report


C# - Question about events (also textbox clearing and starting/stopping a timer)

Hi,


I edited my original post to add snippet of my current code.


How to calculate sentiment score of content faster in c#

Open the connection outside of the foreach




MySqlCommand cmd = new MySqlCommand("select * from avg_scores where Word='" + word + "'", con);
con.Open();
MySqlDataReader r = cmd.ExecuteReader();
foreach (string word in postContent)
{
if (r.Read())
{
this.TempDiff = Math.Abs(Convert.ToDouble(r["Pos"]) - Convert.ToDouble(r["Neg"]));
double tempPos = Convert.ToDouble(r["Pos"]);
double tempNeg = Convert.ToDouble(r["Neg"]);
if (!(tempPos==0.0 && tempNeg==0.0))
{
if (tempPos != 0.0 && tempNeg == 0.0)
{
this.PosScore = this.PosScore + tempPos;
this.PosWordCounter++;
}
if (tempPos == 0.0 && tempNeg != 0.0)
{
this.NegScore = this.NegScore + tempPos;
this.NegWordCounter++;
}
if (this.TempDiff>0.1)
{

if (tempPos>tempNeg)
{
this.PosScore = this.PosScore + tempPos;
this.PosWordCounter++;
}
else
{
this.NegScore = this.PosScore + tempNeg;
this.NegWordCounter++;
}
}
else
{
this.PosScore = this.PosScore + tempPos;
this.NegScore = this.NegScore + tempNeg;
this.ContradictoryWordsCounter++;
if (tempPos > 0.1)
this.PosWordCounter++;
if (tempNeg > 0.1)
this.NegWordCounter++;
}
}

}

}
con.Close();


Avoid use the * on the sql query, use the name of fields;





João Antonio Marques





How to calculate sentiment score of content faster in c#

You're very welcome, hope you'll stick to 'select * from table' from now on ;)

C# - Question about events (also textbox clearing and starting/stopping a timer)

Hi all,


I basically have a System.Timers.Timer that is set to trigger an event every 10 seconds. In the event, I used textbox.Clear(); so that every time the event is triggered, the textbox clears. Unfortunately, this does not work. I also tried textbox.Text = ""; but it still does not work. The textbox is not clearing. Any idea why this happens?


In the beginning of the event, I also wrote this line: myTimer.Enabled = false; to temporarily stop the timer when the event starts. I also wrote this line: myTimer.Enabled = true; just before the event ends to start the timer again. Basically I don't want it to start/trigger the event again while the event is not yet finished executing. Is it okay to do this? or is there a better way to do this?


Please let me know. Thanks





C# - Question about events (also textbox clearing and starting/stopping a timer)

Can you submit your codes or sample code onto SyDrive for us to download to see?




If you think one reply solves your problem, please mark it as An Answer , if you think someone's reply helps you, please mark it as a Proposed Answer



Help by clicking:

Click here to donate your rice to the poor

Click to Donate

Click to feed Dogs & Cats




Found any spamming-senders? Please report at: Spam Report


How do make the texbox accept only numerics, del key and backspace?

hi friends,


is there away to make a textbox accept only numeric, del key and backspace key?


I used the following code but it doesn't work:



private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ( char.IsDigit(e.KeyChar) == true || e.KeyChar == Convert.ToChar(Keys.Back) || e.KeyChar == Convert.ToChar(Keys.Delete) )
{
e.Handled = true;
}
}



thanks


I use Visual studio 2010 professional and SQL server 2008 developer edition!


How do make the texbox accept only numerics, del key and backspace?

How do make the texbox accept only numerics, del key and backspace?


public partial class Form1 : Form
{
/// <summary>
/// Whether Del is pressed or not
/// </summary>
private bool isDelPressed = false;

public Form1()
{
InitializeComponent();
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
int n = (int)e.KeyChar;
e.Handled = !(n == 8 || (n >= 48 && n <= 57) || isDelPressed);
}

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
isDelPressed = (e.KeyCode == Keys.Delete);
}
}



If you think one reply solves your problem, please mark it as An Answer , if you think someone's reply helps you, please mark it as a Proposed Answer



Help by clicking:

Click here to donate your rice to the poor

Click to Donate

Click to feed Dogs & Cats




Found any spamming-senders? Please report at: Spam Report


C# - Question about events (also textbox clearing and starting/stopping a timer)

Hi all,


I basically have a System.Timers.Timer that is set to trigger an event every 10 seconds. In the event, I used textbox.Clear(); so that every time the event is triggered, the textbox clears. Unfortunately, this does not work. I also tried textbox.Text = ""; but it still does not work. The textbox is not clearing. Any idea why this happens?


In the beginning of the event, I also wrote this line: myTimer.Enabled = false; to temporarily stop the timer when the event starts. I also wrote this line: myTimer.Enabled = true; just before the event ends to start the timer again. Basically I don't want it to start/trigger the event again while the event is not yet finished executing. Is it okay to do this? or is there a better way to do this?


Please let me know. Thanks





Update to the database was only read the first value in program

Hai everyone, i have a problem, the program just read the first entered `Quantity` value in the program and apply it to all rows in database and the value of first and second row are same, even though in the beginning, first and second row value are different. First of all, my database is like this (Screenshot 1). The screenshot 1 until screenshot 5 are working properly, i just want to show you to not confuse you later. My problem is on screenshot 6 and 7.



Screenshot 1:

https://www.dropbox.com/s/5q8pyztqy7ejupy/Capture.PNG



And when i run the program and entered the first "Product Code" in first row and want to change the first `Quantity` value to 25, so i just enter 75 in `Quantity` in the program like the screenshot below (Screenshot 2):



Screenshot 2:

https://www.dropbox.com/s/wd9oz7wdi7s4l0k/Capture_1.PNG



And when i click update, the database changed to this (Screenshot 3):



Screenshot 3:

https://www.dropbox.com/s/9i0zc285netfrg3/Capture2.PNG



When i change the first "Product Code" in first row to second "Product Code" in first row and want to change the second `Quantity` value to 100, so i just enter 50 in `Quantity` in the program like the screenshot below (Screenshot 4):



Screenshot 4:

https://www.dropbox.com/s/khsvh5bf1dc4c8u/Capture_2.PNG



And when i click update, the database changed to this (Screenshot 5):



Screenshot 5:

https://www.dropbox.com/s/kdsyd2csccim63w/Capture3.PNG



But, when i enter the first "Product Code" in first row and second "Product code" in second row in my program like the screenshot below (Screenshot 6):



Screenshot 6:

https://www.dropbox.com/s/7hmsoe4ba5n18re/Capture_3.PNG



And when i click update, the database changed to this (Screenshot 7):



Screenshot 7:

https://www.dropbox.com/s/1mmtkz71f8s4u2h/Capture4.PNG.


I have been wondering, why it become like this?



Here is the code:



private void UpdateQuantity()
{
int codeValue = 0;
int index = 0;

List<int> integers = new List<int>();

foreach (var tb in textBoxCodeContainer)
{
if (int.TryParse(tb.Text, out codeValue))
{
integers.Add(codeValue);
}
}

using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
string commandSelect = "SELECT [Quantity], [Description], [Price] FROM [Seranne] WHERE [Code] = @Code";
string commandUpdate = "UPDATE [Seranne] SET [Quantity] = @Quantity WHERE [Code] IN(" + string.Join(", ", integers) + ")";

using (OleDbCommand cmdSelect = new OleDbCommand(commandSelect, conn))
using (OleDbCommand cmdUpdate = new OleDbCommand(commandUpdate, conn))
{
cmdSelect.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
cmdSelect.Parameters["Code"].Value = this.textBoxCodeContainer[index].Text;

cmdUpdate.Parameters.Add("Quantity", System.Data.OleDb.OleDbType.Integer);

using (OleDbDataReader dReader = cmdSelect.ExecuteReader())
{
while (dReader.Read())
{
if (textBoxQuantityContainer[index].Value != 0)
{
newVal = Convert.ToInt32(dReader["Quantity"].ToString()) - textBoxQuantityContainer[index].Value;
cmdUpdate.Parameters["Quantity"].Value = newVal;
int numberOfRows = cmdUpdate.ExecuteNonQuery();
}
}

index += 1;

dReader.Close();
}
}

conn.Close();
}
}

Could you guys help me out? Thanks a bunch!


Update to the database was only read the first value in program

Ah, a continuation from your previous thread! But, I think I just figured it out.


Put your index += 1 statement inside the while loop instead of outside the while loop ... I don't know how I missed that one previously, but I'm pretty sure that's the cause.




~~Bonnie Berent DeWitt [C# MVP]


http://geek-goddess-bonnie.blogspot.com


Update to the database was only read the first value in program

That's not the cause miss, i already tried put the:

index += 1;

in the while loop, and the result still same.

How do make the texbox accept only numerics, del key and backspace?

hi friends,


is there away to make a textbox accept only numeric, del key and backspace key?


I used the following code but it doesn't work:



private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if ( char.IsDigit(e.KeyChar) == true || e.KeyChar == Convert.ToChar(Keys.Back) || e.KeyChar == Convert.ToChar(Keys.Delete) )
{
e.Handled = true;
}
}



thanks


I use Visual studio 2010 professional and SQL server 2008 developer edition!


how to access an XAML control from code

Ok I got it fixed thanks to you. here is what I found


http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2


I implemented the INotifyPropertyChanged


working perfect now.


sweet


how to access an XAML control from code

here is the class with the changes



public class Viapoints : INotifyPropertyChanged

{
private string _simpleAddress;
private string civicNumber;
private string civicName;
private string civicCity;
private string civicPostalCode;
private string civicProvince;
private string viaType;


public Viapoints()
{


}

public Viapoints(string simpleAddress, string viatype)
{
this._simpleAddress = simpleAddress;
this.ViaType = viatype;


}
public Viapoints(string cnumber, string cname, string ccity,string cpostalcode, string cprovince)
{
this.civicNumber = cnumber;
this.civicName = cname;
this.civicCity = ccity;
this.civicPostalCode = cpostalcode;
this.civicProvince = cprovince;
}

public string SimpleAddress
{
get { return _simpleAddress; }
set { _simpleAddress = value;
NotifyPropertyChanged();
}

}
public string ViaType
{
get { return viaType; }
set { viaType = value; }

}
public string CivicNumber
{
get { return civicNumber; }
set { civicNumber = value; }
}

public string CivicName
{
get { return civicName; }
set { civicName = value; }
}

public string CivicCity
{
get { return civicCity; }
set { civicCity = value; }
}

public string CivicPostalCode
{
get { return civicPostalCode; }
set { civicPostalCode = value; }
}

public string CivicProvince
{
get { return civicProvince; }
set { civicProvince = value; }
}

public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}


}


how to access an XAML control from code

what do you recommend I do if I want to populate a list box with countries states/provinces ?


what I want is the user to select what default country state/province the search will be based on.


Write the prime Number code which output like this?


using System;
using System.Collections.Generic;

namespace Csharp
{
public class MainTest
{
static bool IsPrime(int num)
{
for (int i = 2; i <= Math.Sqrt(num); i++)
{
if (num % i == 0) return false;
}
return true;
}
static void Main(string[] args)
{
int num = 0;
//Count how many prime numbers are generated
int counter = 0;
Console.WriteLine("Please input a number:");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Results are:");
for (int i = 2; i <int.MaxValue; i++)
{
if (IsPrime(i))
{
Console.WriteLine(i);
counter++;
if (counter == num)
{
break;
}
}
}
}
}
}



If you think one reply solves your problem, please mark it as An Answer , if you think someone's reply helps you, please mark it as a Proposed Answer



Help by clicking:

Click here to donate your rice to the poor

Click to Donate

Click to feed Dogs & Cats




Found any spamming-senders? Please report at: Spam Report


Write the prime Number code which output like this?


using System;
using System.Collections.Generic;

namespace Csharp
{
public class MainTest
{
public static List<int> primes = new List<int>();

static bool IsPrime(int num)
{
for (int i = 0; i < primes.Count; i++)
{
if (num % primes[i] == 0) return false;
}
return true;
}
static void Main(string[] args)
{
int num = 0;
//Count how many prime numbers are generated
int counter = 0;
Console.WriteLine("Please input a number:");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Results are:");
for (int i = 2; i < int.MaxValue; i++)
{
if (IsPrime(i))
{
primes.Add(i);
Console.WriteLine(i);
counter++;
if (counter == num)
{
break;
}
}
}
}
}
}




Write the prime Number code which output like this?

exstud,


Welcome to here.


If you have codes most similar to mine, you can just add some words instead of copying my codes fully, if you think there's something wrong with my codes, you can just copy some sentences here and point out why this is wrong, maybe this is better;)




If you think one reply solves your problem, please mark it as An Answer , if you think someone's reply helps you, please mark it as a Proposed Answer



Help by clicking:

Click here to donate your rice to the poor

Click to Donate

Click to feed Dogs & Cats




Found any spamming-senders? Please report at: Spam Report


Write the prime Number code which output like this?

@MVP


I did forget to write some english, sorry for that.


The reason why your code is inefficient is because its complexity is linear to the size of the sqrt of the number to be checked, while my adapted version is linear to the size of the primes list.


A prime number is a number that always has a rest fraction when divided by any natural number < itself and > 1.


So say we're looking to see if x is prime, suppose there exists a number n with the properties n < x, n > 1, x % n = 0. Our x is not a prime, but what about n? If n is a prime it's all good (it's in the primes List<int>) but if it's not a prime that would mean there exists natural numbers r, s for which r > 1, r < n, n % r = 0, n = rs. Substituting that in the equation above gets us x % rs = 0 which implies x % r = 0 and x % s = 0. So in this case it would've been sufficient to check the rest fraction of x divided by the smaller numbers r and s instead of n, which completes the proof ;)


Also, sometimes a piece of code says more than a thousand words, if i were to really clean up your code (untested):




using System;
using System.Linq;
using System.Collections.Generic;

namespace Csharp
{
public class MainTest
{
static List<int> primes = new List<int>();

static bool IsPrime(int num)
{
return (from x in primes where num % x == 0 select x).Count() == 0;
}

static void Main(string[] args)
{
Console.WriteLine("Please input a number:");
int num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Results are:");
int cnt = 1;
while (primes.Count < num)
{
cnt++;
if (!IsPrime(cnt))
continue;
primes.Add(cnt);
Console.WriteLine(cnt);
}
}
}
}



have a good day











Write the prime Number code which output like this?

Exstud,


Very good! You think that a non-prime number can be always divided into several prime numbers multiplied together……


I'll mark yours as a purposed answer;)




If you think one reply solves your problem, please mark it as An Answer , if you think someone's reply helps you, please mark it as a Proposed Answer



Help by clicking:

Click here to donate your rice to the poor

Click to Donate

Click to feed Dogs & Cats




Found any spamming-senders? Please report at: Spam Report


Pass type as string variable

I was thinking something like



public class ValueProcessor : IValueProcessor
{
public ClusterResource ClusterResource(string data)
{
//return something here
}
///////////////////.................

and





public interface IValueProcessor
{
string ClusterResource(string data);
///////////////.....
}

And



private readonly IValueProcessor _valueProcessor;
public SwitchDemo(IValueProcessor valueProcessor)
{
_valueProcessor = valueProcessor;
}



again this is untested

oraoledb.oracle not registered on local machine


Hello Guys


I have a C# application which runs fine on a 32 bit environment using a 32 bit client and having MSDAORA as the provider.


Now i need to migrate that to a 64 bit environment.


First question would be what oracle i need to install with what components? 32 bit or 64 bit oracle.


I installed the 32 bit client. I got the error OraOLEDB.oracle not registered on the local machine.


I tried registering the dll throught the regsvr32 command also have set the path variable.


IS there anything else i should be trying? or any solutions would be welcome thanks



OpenData Source Insert

Hi Priya,


With your requirement, we can specify the column lists in both of the insert sub phrase and the select sub phrase, for example:



insert into [TestServerTable] (col1,col2)
select col1,col2 from OPENDATASOURCE('SQLNCLI',
'Data Source=LinkedServerName;Integrated Security=SSPI')
.[DBname].[SchemaName].[DevServerTable]

In this way, the identity column will be filled with identity value manually, and status column will be filled with null (please make sure this column allows null, otherwise, please provide a default value for it).




Allen Li

TechNet Community Support



how to access an XAML control from code

After reading the above links the code makes better sense. i will continue digging in the links further more. Thanks


how to access an XAML control from code

addresses

how to access an XAML control from code

Thank you looks nice.

how to access an XAML control from code



I of course changed the code because I want to experiment and learn, I get this problem that the WaypointList listview doesn't update when I try to edit one of the items. the adding and deleting part works perfectly.


basically what I did is create a class that will hold the data and then add waypoints using the class.


here is the code for only the edit part and the XAML. if needed other parts please let me know.


Thank you


XAML


--------------



<ListView x:Name="WaypointList" ManipulationDelta="ListViewManipulationDelta" Background="#33309501" BorderBrush="#FF309501"
BorderThickness="2" ManipulationMode="All" Visibility="Collapsed" Header="Route addresses" HorizontalAlignment="Right"
VerticalAlignment="Center">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Width="Auto">
<TextBlock Text="{Binding Path=ViaType}" FontWeight="Bold" Margin="10,0,0,0" FontSize="18" Foreground="Black" />
<TextBlock Text="{Binding Path=SimpleAddress}" Margin="20,0,0,0" FontWeight="Bold" FontSize="18" Foreground="Black" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.RenderTransform>
<TranslateTransform />
</ListView.RenderTransform>
</ListView>

here is the edit part


-------------------------



private void Edit_Click(object sender, RoutedEventArgs e)
{
var selectedIndex = WaypointList.SelectedIndex;
NewItem.Text = WayPoints[selectedIndex].SimpleAddress;
DialogButton.Content = "Change";
EntryDialog.IsOpen = true;

NewItem.Focus(FocusState.Programmatic);

}

here is how I instantiate the class



ObservableCollection<Viapoints> WayPoints;

public MainPage()
{
this.InitializeComponent();
WayPoints = new ObservableCollection<Viapoints>();
WaypointList.ItemsSource = WayPoints;

}


the edit is actually happening in the class but not in the listview


I hope it has some sense.


thank you



how to access an XAML control from code

i got a textbox control that for some reason I cannot set its text propertie from code. I think because it is part of data template but not sure. is there a way to access it. here is the XAML code.


I need to change the UnitUsedTextBlock.Text . thank you



<ListView x:Name="RouteResultsListView" ItemsSource="{Binding RouteLegs}" Width="400" Height="540" HorizontalAlignment="Left" SelectionMode="None" ScrollViewer.VerticalScrollBarVisibility="Disabled">
<ListView.ItemTemplate>
<DataTemplate >
<ListBox ItemsSource="{Binding ItineraryItems}" Height="499">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<TextBlock Text="{Binding Instruction.Text}"
TextWrapping="Wrap" MaxLines="5" Width="200" />
<TextBlock Text="{Binding TravelDistance}"
Margin="10,0,0,0" />
<TextBlock x:Name="UnitUsedTextBlock" Margin="5,0,0,0" Text="km" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>



how to access an XAML control from code

I would use data binding to bind the Text property to a StaticResource that can be changed in the code behind.


1. Add a class with INotifyProperty change interface to act as the container for Units (This class could be useful for other places in your application as well.)



public class ViewModel : INotifyPropertyChanged
{
private string units;
public string Units
{
get { return units; }
set
{
units = value;
RaisePropertyChanged();
}
}

public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged([CallerMemberName] string caller = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
}
}

2. Instantiate this class as a StaticResource in Page.Resources



<Page.Resources>
<local:ViewModel x:Key="myVM" />
</Page.Resources>

3. Add the data binding to your TextBlock in the DataTemplate



<TextBlock Text="{Binding Units, Source={StaticResource myVM}}" Margin="5,0,0,0" />

4. In the code behind, access the Units like this:



var vm = this.Resources["myVM"] as ViewModel;
vm.Units = "km";

When you change vm.Units, the display will also change.


Consuming webservice in C#

You try do right-clicking on your project, then select Add Service Reference... The next, you enter web service URL and click Go.


Please let me know if any problem


Hope this will help you!!


Consuming webservice in C#

Hi,


Can you talk to anyone without any device e.g., cellphone,landline?


Between you and your client phone is the proxy via which you communicate. Similarly, is SOA, your own code will communicate with service via proxy object. It is mandatory.


Using SOAP UI tool you can generate wsdl and then using SvcUtil.exe you can generate proxy class.


Using export definition you can create wsdl.


Alternatively you can generate proxy directly by SvcUtil. But I prefer SOAP UI since it provides some more features.




One good question is equivalent to ten best answers.



Consuming webservice in C#

Hi all, Thank you all for the replies.


I ran svcutil. I got a proxy file generated, which i have attached here. Attached the WSDL file also. The webservice method name is wsadd. It takes 2 intergers and returns their Sum. In the attached Proxy file which class should i instantiate and which method should i invoke to invoke the webservice. Pls advice.


Thanks,


Sai



//------------------------------------------------------------------------------

// <auto-generated>

// This code was generated by a tool.

// Runtime Version:2.0.50727.5472

//

// Changes to this file may cause incorrect behavior and will be lost if

// the code is regenerated.

// </auto-generated>

//------------------------------------------------------------------------------







[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]

[System.ServiceModel.ServiceContractAttribute(Namespace="urn:hpccsystems:ecl:wsadd", ConfigurationName="roxieServiceSoap")]

public interface roxieServiceSoap

{



// CODEGEN: Generating message contract since the wrapper name (wsaddRequest) of message wsaddRequest does not match the default value (wsadd)

[System.ServiceModel.OperationContractAttribute(Action="/roxie/wsadd?ver_=1.0", ReplyAction="*")]

[System.ServiceModel.XmlSerializerFormatAttribute()]

wsaddResponse wsadd(wsaddRequest request);

}



/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "3.0.4506.648")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:hpccsystems:ecl:wsadd")]

public partial class ArrayOfEspException

{



private string sourceField;



private EspException[] exceptionField;



/// <remarks/>

[System.Xml.Serialization.XmlElementAttribute(Order=0)]

public string Source

{

get

{

return this.sourceField;

}

set

{

this.sourceField = value;

}

}



/// <remarks/>

[System.Xml.Serialization.XmlElementAttribute("Exception", Order=1)]

public EspException[] Exception

{

get

{

return this.exceptionField;

}

set

{

this.exceptionField = value;

}

}

}



/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "3.0.4506.648")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:hpccsystems:ecl:wsadd")]

public partial class EspException

{



private string codeField;



private string audienceField;



private string sourceField;



private string messageField;



/// <remarks/>

public string Code

{

get

{

return this.codeField;

}

set

{

this.codeField = value;

}

}



/// <remarks/>

public string Audience

{

get

{

return this.audienceField;

}

set

{

this.audienceField = value;

}

}



/// <remarks/>

public string Source

{

get

{

return this.sourceField;

}

set

{

this.sourceField = value;

}

}



/// <remarks/>

public string Message

{

get

{

return this.messageField;

}

set

{

this.messageField = value;

}

}

}



/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "3.0.4506.648")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:hpccsystems:ecl:wsadd")]

public partial class wsaddResponseResults

{



private wsaddResponseResultsResult resultField;



/// <remarks/>

public wsaddResponseResultsResult Result

{

get

{

return this.resultField;

}

set

{

this.resultField = value;

}

}

}



/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "3.0.4506.648")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:hpccsystems:ecl:wsadd")]

public partial class wsaddResponseResultsResult

{



private Dataset datasetField;



/// <remarks/>

[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:hpccsystems:ecl:wsadd:result:result_1")]

public Dataset Dataset

{

get

{

return this.datasetField;

}

set

{

this.datasetField = value;

}

}

}



/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "3.0.4506.648")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:hpccsystems:ecl:wsadd:result:result_1")]

public partial class Dataset

{



private DatasetRow[] rowField;



private string nameField;



/// <remarks/>

[System.Xml.Serialization.XmlElementAttribute("Row", Order=0)]

public DatasetRow[] Row

{

get

{

return this.rowField;

}

set

{

this.rowField = value;

}

}



/// <remarks/>

[System.Xml.Serialization.XmlAttributeAttribute()]

public string name

{

get

{

return this.nameField;

}

set

{

this.nameField = value;

}

}

}



/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("svcutil", "3.0.4506.648")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="urn:hpccsystems:ecl:wsadd:result:result_1")]

public partial class DatasetRow

{



private string result_1Field;



/// <remarks/>

[System.Xml.Serialization.XmlElementAttribute(DataType="integer", Order=0)]

public string Result_1

{

get

{

return this.result_1Field;

}

set

{

this.result_1Field = value;

}

}

}



[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]

[System.ServiceModel.MessageContractAttribute(WrapperName="wsaddRequest", WrapperNamespace="urn:hpccsystems:ecl:wsadd", IsWrapped=true)]

public partial class wsaddRequest

{



[System.ServiceModel.MessageBodyMemberAttribute(Namespace="urn:hpccsystems:ecl:wsadd", Order=0)]

[System.Xml.Serialization.XmlElementAttribute(DataType="integer")]

public string i1;



[System.ServiceModel.MessageBodyMemberAttribute(Namespace="urn:hpccsystems:ecl:wsadd", Order=1)]

[System.Xml.Serialization.XmlElementAttribute(DataType="integer")]

public string i2;



public wsaddRequest()

{

}



public wsaddRequest(string i1, string i2)

{

this.i1 = i1;

this.i2 = i2;

}

}



[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]

[System.ServiceModel.MessageContractAttribute(WrapperName="wsaddResponse", WrapperNamespace="urn:hpccsystems:ecl:wsadd", IsWrapped=true)]

public partial class wsaddResponse

{



[System.ServiceModel.MessageBodyMemberAttribute(Namespace="urn:hpccsystems:ecl:wsadd", Order=0)]

public ArrayOfEspException Exceptions;



[System.ServiceModel.MessageBodyMemberAttribute(Namespace="urn:hpccsystems:ecl:wsadd", Order=1)]

public wsaddResponseResults Results;



[System.ServiceModel.MessageBodyMemberAttribute(Namespace="urn:hpccsystems:ecl:wsadd", Order=2)]

[System.Xml.Serialization.XmlAttributeAttribute()]

public int sequence;



public wsaddResponse()

{

}



public wsaddResponse(ArrayOfEspException Exceptions, wsaddResponseResults Results, int sequence)

{

this.Exceptions = Exceptions;

this.Results = Results;

this.sequence = sequence;

}

}



[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]

public interface roxieServiceSoapChannel : roxieServiceSoap, System.ServiceModel.IClientChannel

{

}



[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]

public partial class roxieServiceSoapClient : System.ServiceModel.ClientBase<roxieServiceSoap>, roxieServiceSoap

{



public roxieServiceSoapClient()

{

}



public roxieServiceSoapClient(string endpointConfigurationName) :

base(endpointConfigurationName)

{

}



public roxieServiceSoapClient(string endpointConfigurationName, string remoteAddress) :

base(endpointConfigurationName, remoteAddress)

{

}



public roxieServiceSoapClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :

base(endpointConfigurationName, remoteAddress)

{

}



public roxieServiceSoapClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :

base(binding, remoteAddress)

{

}



[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]

wsaddResponse roxieServiceSoap.wsadd(wsaddRequest request)

{

return base.Channel.wsadd(request);

}



public ArrayOfEspException wsadd(string i1, string i2, out wsaddResponseResults Results, out int sequence)

{

wsaddRequest inValue = new wsaddRequest();

inValue.i1 = i1;

inValue.i2 = i2;

wsaddResponse retVal = ((roxieServiceSoap)(this)).wsadd(inValue);

Results = retVal.Results;

sequence = retVal.sequence;

return retVal.Exceptions;

}

}










<?xml version="1.0" encoding="utf-8"?>
<definitions xmlns:tns="urn:hpccsystems:ecl:wsadd" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:hpccsystems:ecl:wsadd" xmlns="http://schemas.xmlsoap.org/wsdl/">
<types>
<xsd:schema xmlns:ds1="urn:hpccsystems:ecl:wsadd:result:result_1" elementFormDefault="qualified" targetNamespace="urn:hpccsystems:ecl:wsadd">
<xsd:import schemaLocation="../result/Result_1.xsd" namespace="urn:hpccsystems:ecl:wsadd:result:result_1" />
<xsd:complexType name="EspException">
<xsd:all>
<xsd:element minOccurs="0" name="Code" type="xsd:string" />
<xsd:element minOccurs="0" name="Audience" type="xsd:string" />
<xsd:element minOccurs="0" name="Source" type="xsd:string" />
<xsd:element minOccurs="0" name="Message" type="xsd:string" />
</xsd:all>
</xsd:complexType>
<xsd:complexType name="ArrayOfEspException">
<xsd:sequence>
<xsd:element minOccurs="0" name="Source" type="xsd:string" />
<xsd:element minOccurs="0" maxOccurs="unbounded" name="Exception" type="tns:EspException" />
</xsd:sequence>
</xsd:complexType>
<xsd:element name="Exceptions" type="tns:ArrayOfEspException" />
<xsd:complexType name="EspStringArray">
<xsd:sequence>
<xsd:element minOccurs="0" maxOccurs="unbounded" name="Item" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="EspIntArray">
<xsd:sequence>
<xsd:element minOccurs="0" maxOccurs="unbounded" name="Item" type="xsd:int" />
</xsd:sequence>
</xsd:complexType>
<xsd:simpleType name="XmlDataSet">
<xsd:restriction base="xsd:string" />
</xsd:simpleType>
<xsd:simpleType name="CsvDataFile">
<xsd:restriction base="xsd:string" />
</xsd:simpleType>
<xsd:simpleType name="RawDataFile">
<xsd:restriction base="xsd:base64Binary" />
</xsd:simpleType>
<xsd:element name="wsaddRequest">
<xsd:complexType>
<xsd:all>
<xsd:element minOccurs="0" maxOccurs="1" name="i1" type="xsd:integer" />
<xsd:element minOccurs="0" maxOccurs="1" name="i2" type="xsd:integer" />
</xsd:all>
</xsd:complexType>
</xsd:element>
<xsd:element name="wsaddResponse">
<xsd:complexType>
<xsd:all>
<xsd:element minOccurs="0" name="Exceptions" type="tns:ArrayOfEspException" />
<xsd:element minOccurs="0" name="Results">
<xsd:complexType>
<xsd:all>
<xsd:element name="Result">
<xsd:complexType>
<xsd:all>
<xsd:element minOccurs="0" ref="ds1:Dataset" />
</xsd:all>
</xsd:complexType>
</xsd:element>
</xsd:all>
</xsd:complexType>
</xsd:element>
</xsd:all>
<xsd:attribute name="sequence" type="xsd:int" />
</xsd:complexType>
</xsd:element>
<xsd:element name="string" nillable="true" type="xsd:string" />
</xsd:schema>
</types>
<message name="wsaddSoapIn">
<part name="parameters" element="tns:wsaddRequest" />
</message>
<message name="wsaddSoapOut">
<part name="parameters" element="tns:wsaddResponse" />
</message>
<portType name="roxieServiceSoap">
<operation name="wsadd">
<input message="tns:wsaddSoapIn" />
<output message="tns:wsaddSoapOut" />
</operation>
</portType>
<binding name="roxieServiceSoap" type="tns:roxieServiceSoap">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" />
<operation name="wsadd">
<soap:operation soapAction="/roxie/wsadd?ver_=1.0" style="document" />
<input>
<soap:body use="literal" />
</input>
<output>
<soap:body use="literal" />
</output>
</operation>
</binding>
<service name="roxie">
<port name="roxieServiceSoap" binding="tns:roxieServiceSoap">
<soap:address location="http://192.168.19.130:8002/WsEcl/soap/query/roxie/wsadd" />
</port>
</service>
</definitions>


Consuming webservice in C#

I have never used no stinking srvcutil! :) You should be able to make the call in code like what was shown in the link provided.

Consuming webservice in C#

You would call


wsaddResponse wsadd(wsaddRequest request);


Something like



var req = new wsaddRequest();

req.i1 = 2;

req.i2 = 4;

var response = proxy.wsadd(req);

var results = response.Results;



David




David http://blogs.msdn.com/b/dbrowne/



Consuming webservice in C#

You might also want to take a look at my blog post about creating a generic WCF proxy class:


http://geek-goddess-bonnie.blogspot.com/2012/09/a-generic-wcf-proxy-class.html




~~Bonnie Berent DeWitt [C# MVP]


http://geek-goddess-bonnie.blogspot.com


C# Coding help

I am a novice when it comes to programming, but do have a slight understanding of how. I read a lot of C# books and patterns books, and I am stumped on how to perform something. So basically what I am trying to do, is I have a base class which has all properties and methods that I need. I then will have 1 to n child classes that will inherit the base class, these child classes will only contain some new properties, and will override a method in the base class.


I am not sure if I am going about it the wrong way or not, like I said I am a novice, but I am not sure what class will need to be created, so based on some patterns I created a factory class, that creates the proper class based on users choice. When I instantiate the classes I to them as the base class, and because I do this, I cannot access the properties in the child classes, and I am curious on how to go about doing it properly. Below is a code example, to give an understanding of what I mean, as I am obviously going about it the wrong way, or I am just missing something, but any help is greatly appreciated, in my learning experience.



namespace Test
{
public enum ClassTypes
{
ChildClass,
Default
}

public class BaseClass
{
public Int64 Id { get; set; }
public string Details { get; set; }

// Child classes will override this method
public virtual void Save()
{
Console.WriteLine("Saving.....");
Console.WriteLine("Id: {0} - Details: {1}", this.Id, this.Details);
}
}

public class ChildClass : BaseClass
{
public string ExtraDetails { get; set; }

public override void Save()
{
// Call base's save method
base.Save();
Console.WriteLine("Extra Details: {0}", this.ExtraDetails);
}
}

// Factory Class to instansiate proper class
public static class ClassFactory
{
public static BaseClass CreateClass(ClassTypes classType)
{
switch (classType)
{
case ClassType.ChildClass:
return new ChildClass();
default:
return new BaseClass();
}
}
}

class Program
{
static void Main(string[] args)
{
BaseClass bc1 = ClassFactory.CreateClass(ClassTypes.Default);
BaseClass bc2 = ClassFactory.CreateClass(ClassTypes.ChildClass);

IList<BaseClass> list = new List<BaseClass>();

bc1.Id = 1;
bc.Details = "Testing Base Class";
list.Add(bc1);

bc2.Id = 2;
bc2.Details = "Testing child class";
// Can NOT access because type being BaseClass
bc2.ExtraDetails = "Extended testing";
list.Add(bc2);

foreach (BaseClass bc list)
{
bc.Save();
}

Console.ReadLine();
}
}
}





If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.



Don't Retire Technet


C# Coding help

I'm not sure exactly what you're asking - but you could use a generic method:



public static T CreateClass<T>() where T : BaseClass
{





Reed Copsey, Jr. - http://reedcopsey.com - If a post answers your question, please click Mark As Answer on that post. If you find a post helpful, please click Vote as Helpful.


C# Coding help

I think my problem is because I am a novice, and from reading so many things, I am over complicating things from over thinking. I couldn't get the generics to work, so instead I just create each class as is, so one BaseClas and one ChildClass, then add them to the generic list of type BaseClass and things seem to work as should, I am just unsure if this is the way to approach it or not, as I am sure it will become easier with experience. Thank you for your input Reed.


If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.



Don't Retire Technet


C# Coding help

This is something C# only coders don't easily understand.


To achieve what you want, replace



// Can NOT access because type being BaseClass
bc2.ExtraDetails = "Extended testing";

by this



// CAN access despite type being BaseClass - if it is an instance of ChildClass
ChildClass cc = bc2 as ChildClass;
if (cc != null)
cc.ExtraDetails = "Extended testing";

I'm assuming the BaseClass is not under your control, otherwise the code could be (and should be) easier.



C# Coding help


This is something C# only coders don't easily understand.


To achieve what you want, replace



// Can NOT access because type being BaseClass
bc2.ExtraDetails = "Extended testing";

by this



// CAN access despite type being BaseClass - if it is an instance of ChildClass
ChildClass cc = bc2 as ChildClass;
if (cc != null)
cc.ExtraDetails = "Extended testing";

I'm assuming the BaseClass is not under your control, otherwise the code could be (and should be) easier.




The code is under my control, what I am trying to do, is I have a base class that I created with all of the properties and methods I need to work with it. Each child class will inherit, the base class to add some extra properties, depeneding on what the child class is for. The child class will override the base class Save method, which first it will call the base.Save(), to save all the inherited properties to the base table, and then the child class will save the extended properties to a different table.


I do not want all the data in one table as each child class has different information, so I would have a table with a lot of null values. I hope I am making since and looking at it correctly.




If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.



Don't Retire Technet


C# Coding help

Reed's suggestion to use Generics for your ClassFactory should have helped you. You said you couldn't get it to work. Can you post the code you tried and where you ran into problems?


~~Bonnie Berent DeWitt [C# MVP]


http://geek-goddess-bonnie.blogspot.com


Type or namespace could not be found - missing directive /assembly reference?

What .NET framework is the example code of that book of yours expecting and does it comply with your coding environment. Check also, if your program is expecting a 32-bit assembly, whereas you've loaded the 64-bit version?


Usually, if a using directive is missing a reference that directive should be underscored by Intellisense with a curled red line. I guess you didn't see such a highlighting in your code?


wizend


Friday, August 30, 2013

Repeating value of the group in Header

Hi ,


To repeat headers for each group - http://www.allaboutmssql.com/2013/08/ssrs-how-to-repeat-headers-for-each.html




sathya --------- Mark as answered if my post solved your problem and Vote as helpful if my post was useful.


Get and use MainWindowHandle for a hidden or minimized window

Many thanks for your kind advice. Much appreciated!


After some enjoyable code wrangling, I can now find the MainWindowHandle of almost any window. One case, however, still eludes me.


If the window I want the handle of is minimised when I start my program, the handle is zero. I can find the associated process of the window easily, but even after a process refresh, the handle is still zero.


If I manually (not programmatically) restore the window, I can find the handle. However, that requires an action on the part of the user, which is highly undesirable.


Interestingly, if I manually restore the window and then minimise it again before I try to find the handle, the handle is still zero.


Questions:



  1. How do I find the handle of a window that is minimised and does not produce a handle on process refresh?

  2. How can I programmatically restore a window from the process alone, not using the handle?


Many thanks for your advice.


Changing the button background color in the event handler with c#

Other than there not being a Color.Red (did you mean Colors .Red?) that works for me. (And other than hardcoding colors, but this is just test code. In production you'd pull the color from a resource and respect high contrast settings).


Can you provide more context? Do you have the button template or contented so that the background isn't visible?


--Rob


Changing the button background color in the event handler with c#

Hello huge_newbie,


You can change your code:



button1.Background = new SolidColorBrush(Windows.UI.Colors.Red);



Repeating value of the group in Header

Hi ,


To repeat headers for each group - http://www.allaboutmssql.com/2013/08/ssrs-how-to-repeat-headers-for-each.html




sathya --------- Mark as answered if my post solved your problem and Vote as helpful if my post was useful.


SQL 2005 SSRS - Date/Time question

I'm having a little trouble understanding what you're asking for? Say a user selects a start date of 08-23-2013 and an end date of 08-28-2013, are you looking for data between '08-23-2013 07:00' and '08-28-2013 07:00'?


If so how about something like:


SELECT Heat_Number, Heat_Idx, Furnace_Idx FROM HeatData


WHERE Turn_Date BETWEEN DATEADD(hh, 7, @Start_Date) AND DATEADD(hh, 7, @End_Date)


How to enable site collection feature by default when deploying a visual webpart from visual studio?

Hi,


I am making a visual web part in SP 2010 using visual studio 2010.


I want it so that when I add and deploy my wsp file, it should by default keep the site collection feature activated for the web part.


I will be deploying through powershell and central admin only on non-dev environment.


Is there a way to do this? Maybe add some special xml to the feature file?


Also I noticed that the first time I deployed it, it was not active, then I activated the feature. Then from that point, if I ever try to retract and remove, then add and deploy, the feature is activated by default. Can anyone explain whats going on here? I would expect the feature to be inactivated by default...







How to enable site collection feature by default when deploying a visual webpart from visual studio?

Use the Powershell Enable-SPFeature after you have deployed the WSP.


How to enable site collection feature by default when deploying a visual webpart from visual studio?

Hi,


Please read the following URL. This is the way to activate and deactivate features programmatically.


Please let me know if you have any doubt.


http://social.msdn.microsoft.com/Forums/sharepoint/en-US/bd9a562e-eeb8-4fd3-a37d-3dc736ff6b56/programmatically-activating-and-deactivating-a-feature



Thanks,




Soumya Das


How to enable site collection feature by default when deploying a visual webpart from visual studio?

Hello,


You need to create batch file when you can add all the commands to add/deploy and activate feature. See below link to create that batch file:


http://apartha77.blogspot.in/2012/05/batch-file-installbat-to-automate.html


Hope it could help




Hemendra:Yesterday is just a memory,Tomorrow we may never see

Please remember to mark the replies as answers if they help and unmark them if they provide no help.


How to enable site collection feature by default when deploying a visual webpart from visual studio?

Hi,


You first part and second part of the questions are conflicting:)


In order to handle the activation of features while deploying your solution, you will have to play around with the feature properties and the project properties of your VS 2010 solution(Deployment Strategy property).


Found a link which perfectly suits your needs,


http://devramblings.wordpress.com/2011/03/23/activate-on-default/



Please let us know whether it helped!!


Regards,


Sharath




sharath kumart shivarama


WinRT Cascading async Calls


private async void engine_SaveRequested(object sender, SaveRestoreEventArgs e)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =>
{
//create a Saved Game folder for saving all the games to app local folder or open existing folder
var savedGameFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("SavedGame", CreationCollisionOption.OpenIfExists);
//set currently saved game folder name
string gameFolderName = DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".save";
//create folder for currently saved game in the SavedGame folder and append a integer value if file name exists
var currentGameFolder = await savedGameFolder.CreateFolderAsync(gameFolderName, CreationCollisionOption.GenerateUniqueName);
//create currently saved game file in the currentGameFolder with the gameFolderName
var savedGameFile = await currentGameFolder.CreateFileAsync(gameFolderName, CreationCollisionOption.ReplaceExisting);
//open savedGameFile stream for writing
var stream = await savedGameFile.OpenStreamForWriteAsync();
e.Stream = stream;
});
}

The above code does not compile.


I've tried to work through it a number of ways, but a solution escapes me.


The point of the function (called from a non-UI task thread) is to do the steps as a transaction. Each step in order with a result so that e.Stream has a file Stream.


I can do this if I block the UI, but I don't want to block. I want it to just run through the statements as they are...I don't care if each statement is asynchronous as long as they run in order and don't end the engine_SaveRequested method until everything is done.


Help?


Dave


C# Coding help

I am a novice when it comes to programming, but do have a slight understanding of how. I read a lot of C# books and patterns books, and I am stumped on how to perform something. So basically what I am trying to do, is I have a base class which has all properties and methods that I need. I then will have 1 to n child classes that will inherit the base class, these child classes will only contain some new properties, and will override a method in the base class.


I am not sure if I am going about it the wrong way or not, like I said I am a novice, but I am not sure what class will need to be created, so based on some patterns I created a factory class, that creates the proper class based on users choice. When I instantiate the classes I to them as the base class, and because I do this, I cannot access the properties in the child classes, and I am curious on how to go about doing it properly. Below is a code example, to give an understanding of what I mean, as I am obviously going about it the wrong way, or I am just missing something, but any help is greatly appreciated, in my learning experience.



namespace Test
{
public enum ClassTypes
{
ChildClass,
Default
}

public class BaseClass
{
public Int64 Id { get; set; }
public string Details { get; set; }

// Child classes will override this method
public virtual void Save()
{
Console.WriteLine("Saving.....");
Console.WriteLine("Id: {0} - Details: {1}", this.Id, this.Details);
}
}

public class ChildClass : BaseClass
{
public string ExtraDetails { get; set; }

public override void Save()
{
// Call base's save method
base.Save();
Console.WriteLine("Extra Details: {0}", this.ExtraDetails);
}
}

// Factory Class to instansiate proper class
public static class ClassFactory
{
public static BaseClass CreateClass(ClassTypes classType)
{
switch (classType)
{
case ClassType.ChildClass:
return new ChildClass();
default:
return new BaseClass();
}
}
}

class Program
{
static void Main(string[] args)
{
BaseClass bc1 = ClassFactory.CreateClass(ClassTypes.Default);
BaseClass bc2 = ClassFactory.CreateClass(ClassTypes.ChildClass);

IList<BaseClass> list = new List<BaseClass>();

bc1.Id = 1;
bc.Details = "Testing Base Class";
list.Add(bc1);

bc2.Id = 2;
bc2.Details = "Testing child class";
// Can NOT access because type being BaseClass
bc2.ExtraDetails = "Extended testing";
list.Add(bc2);

foreach (BaseClass bc list)
{
bc.Save();
}

Console.ReadLine();
}
}
}





If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.



Don't Retire Technet


C# Coding help

I'm not sure exactly what you're asking - but you could use a generic method:



public static T CreateClass<T>() where T : BaseClass
{





Reed Copsey, Jr. - http://reedcopsey.com - If a post answers your question, please click Mark As Answer on that post. If you find a post helpful, please click Vote as Helpful.