How can I call this method using a button? - c#-4.0

public static bool WriteBeamDataToFile(string Filename, List<Part> Parts)
{
// Open a Streamwriter to write data to the specified Filename
using (StreamWriter TeklaDataWriter = new StreamWriter(Filename))
{
// Connect to the Currently Open Tekla Model
Model Model = new Model();
foreach (Part CurrentPart in Parts)
{
if (CurrentPart != null)
{
string Name = CurrentPart.Name;
string Profile = CurrentPart.Profile.ProfileString;
string Material = CurrentPart.Material.MaterialString;
string Finish = CurrentPart.Finish;
TeklaDataWriter.WriteLine(Name + "," + Profile + "," + Material + "," + Finish);
}
}
}
return File.Exists(Filename);
}
Example:
private void button1_Click(object sender, EventArgs e)
{
How to call above method here?
}

private void button1_Click(object sender, EventArgs e) {
private bool isFileExists;
List<Parts> partsList = new List<Parts>();
isFileExists = WriteBeamDataToFile("example.txt",partsList)
if(isFileExists){
//do something..
}
}

Method above is mark as static. That's why you faced some issue.
Static method could be call from Class it' self.
While non static methods could be called from class instance.
See example:
class MyClass {
//static method
public static void Method1() {}
//non static method
public void Method2() {}
}
class MyForm:Form {
...
private void button1_Click(object sender, EventArgs e)
{
//here we call static method of MyClass
MyClass.Method1();
}
//or
private void button1_Click(object sender, EventArgs e)
{
// Here we create an instance of MyClass
var class = new MyClass();
// and call non static Method
class.Method2();
}
}
}

Related

I Want To Itemonclicklister in Fragment on Spinner

This Is Main Fragment
Fragment:
private void getStock() {
dialog.show();
Retrofit retrofit = RetrofitClient.getRetrofitInstance();
apiInterface api = retrofit.create(apiInterface.class);
Call<List<Blocks>>call = api.getVaccineBlocks();
call.enqueue(new Callback<List<Blocks>>() {
#Override
public void onResponse(Call<List<Blocks>>call, Response<List<Blocks>> response) {
if (response.code() == 200) {
block = response.body();
spinnerada();
dialog.cancel();
}else{
dialog.cancel();
}
}
#Override
public void onFailure(Call<List<Blocks>> call, Throwable t) {
dialog.cancel();
}
});
}
private void spinnerada() {
String[] s = new String[block.size()];
for (int i = 0; i < block.size(); i++) {
s[i] = block.get(i).getBlockName();
final ArrayAdapter a = new ArrayAdapter(getContext(), android.R.layout.simple_spinner_item, s);
a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spinner.setAdapter(a);
}
}
This Is Blocks Model
model:
package com.smmtn.book.models;
import java.io.Serializable;
public class Blocks implements Serializable {
public String id;
public String blockName;
public String blockSlug;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBlockName() {
return blockName;
}
public void setBlockName(String blockName) {
this.blockName = blockName;
}
public String getBlockSlug() {
return blockSlug;
}
public void setBlockSlug(String blockSlug) {
this.blockSlug = blockSlug;
}
}
here i need onitemclick with blockslug please any one can help, am new to android so i need some example.when on click i want take blockslug and load another method with that blockslug,like will get data from u "http://example.com/block/"+blockslug
i want to get blockslug from selected block
i hope guys i will get help
and sorry for my bad English,
First of all, you need to implement setOnItemSelectedListener. Refer to this https://stackoverflow.com/a/20151596/9346054
Once you selected the item, you can call them by making a new method. Example like below
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
final String itemSelected = parent.getItemAtPosition(pos).toString();
showBlockSlug(itemSelected);
}
And then, at the method showBlockSlug() , you can call Retrofit.
private void showBlockSlug(final String blockslug){
final String url = "http://example.com/block/"+ blockslug;
//Do your stuff...
}

Google fused location service android

class name is Myclass and implement methods like -> LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener override methds
private static int UPDATE_INTERVAL = 10000; // 10 sec
private static int FATEST_INTERVAL = 5000; // 5 sec
private static int DISPLACEMENT = 10; // 10 meters
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
Context mContext;
#Override
public void onConnected(Bundle bundle) {
mGoogleApiClient = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
createLocationRequest();
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (LocationListener) mContext);
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
// mLocationRequest.setNumUpdates(2);
// mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Ov
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
stopLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
DateFormat.getTimeInstance().format(new Date());
updateUI();
}
public String updateUI() {
if (null != mCurrentLocation) {
Double lat = mCurrentLocation.getLatitude();
Double lng = mCurrentLocation.getLongitude();
Log.d("thhhhhhhhhhhhhhhhhhhh",lat.toString() +lng.toString());
getCurrentlocation(mCurrentLocation);
//setCurrentLocation(String.valueOf(lat + "," + lng));
tLocation(mCurrentLocation);
// arrayList.add(mCurrentLocation);
return lat.toString();
}
return null;
}
private void getCurrentlocation(Location mCurrentLocation) {
}
public void setmCurrentLocation(Location mCurrentLocation) {
this.mCurrentLocation = mCurrentLocation;
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) this);
}
I want to develop mylocation class and getlocation method so its returns lat loan.
How to access that in any class and get lat lon ??
may you need to create servics, that implement google locationAPI , Location listner more..
In that override method onLocationChanged you get lat-long now you can send that direct to your server or other class
i hope My answer is help you.
if don't then ask me again.
thank you.

proxy pattern no suitable methods found to override? Help i'm not sure what just went wrong

This is all in the form...
namespace Proxy_Pattern
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double bankAmount = 1000.00;
private void btnCheck_Click(object sender, EventArgs e)
{
double amount;
amount = double.Parse(txtAmount.Text);
CheckProxy cp =new CheckProxy();
cp.CheckTransactionRequest(amount);
lbltotal.Text = bankAmount.ToString();
}
private void btnCreditCard_Click(object sender, EventArgs e)
{
}
}
abstract class BankSubject
{
public abstract void CreditTransactionRequest(double amount);
public abstract void CheckTransactionRequest(double amount);
}
class RealBankSubject : BankSubject
{
double bank;
public RealBankSubject(double m_bacc)
{
bank = m_bacc;
}
public override void CreditTransactionRequest(double num)
{
bank -= num;
}
public override void CheckTransactionRequest(double num)
{
bank += num;
}
}
Does not implement inherited abstract members.... but why?
class CreditCardProxy : BankSubject
{
RealBankSubject realSubject;
double amount;
public CreditCardProxy (double m_bacc)
{
amount = m_bacc ;
}
no suitable method to override?... how is this an error? I have a method right here?
public override void CreditTransactionRequest()
{
if (realSubject == null)
{
realSubject = new RealBankSubject(amount);
}
realSubject.CreditTransactionRequest(amount);
}
public override void CheckTransactionRequest()
{
}
}
class CheckProxy : BankSubject
{
RealBankSubject realSubject;
double amount;
public override void CreditTransactionRequest()
{
}
public override void CheckTransactionRequest()
{
if (realSubject == null)
{
realSubject = new RealBankSubject(amount);
}
realSubject.CheckTransactionRequest(amount);
}
}
}
In your proxy, you are not specifying the amount as a parameter to the method:
public override void CreditTransactionRequest();
So it cannot override
public abstract void CreditTransactionRequest(double amount);
as the method signature doesn't not match
CreditTransactionRequest in CreditCardProxy does not take any arguments but CreditTransactionRequest in BankSubject does. This is why you can not override the method the signatures do not match.

System.Data.OleDb.OleDbException was unhandled; "Syntax error in INSERT INTO statement" in C# wh

using System.Data.OleDb;
namespace ConnectingToMS_Access1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OleDbDataAdapter da;
DataSet ds;
private void Form1_Load(object sender, EventArgs e)
{
da = new OleDbDataAdapter("Select * from Record", "Provider=Microsoft.Ace.oledb.12.0;data source='D:\\mydb.accdb'");
ds = new DataSet();
da.Fill(ds);
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = ds.Tables[0];
}
private void button2_Click(object sender, EventArgs e)
{
DataRow dr = ds.Tables[0].NewRow();
dr[0] = "abc";
dr[1] = "def";
dr[2] = "ghi";
dr[3] = "jkl";
ds.Tables[0].Rows.Add(dr);
}
private void button3_Click(object sender, EventArgs e)
{
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
da.Update(ds.Tables[0]);
MessageBox.Show("Saved in Database");
}
}
}
You need to explicitly define the named columns in your query.
The problem is that you can't update columns based on column position. It might have been reasonable to expect that calling the Fill method would return both records and column-names, but it probably won't. After all, running that select query will return only data, not schema.

C# - set empty delegate for event

public event EventHandler MyButtonClick = delegate { };
The construction above allows to not check if there is any subscriber:
public virtual void OnMyButtonClick(EventHandler e)
{
this.MyButtonClick(this, e);
}
in stead of
public virtual void OnMyButtonClick(EventHandler e)
{
if (MyButtonClick!=null)
this.MyButtonClick(this, e);
}
But is it really a good idea? Is this the only benefit: to not check if any subscriber exists?
UPDATE: Here is example
namespace ConsoleApplication2
{
public class TestClass
{
public event EventHandler MyButtonClick;
//= delegate { };
public void OnButtonClick(EventArgs e)
{
MyButtonClick(this, e);
}
}
class Program
{
static void Main(string[] args)
{
var testClass = new TestClass();
//it throws an exception
testClass.OnButtonClick(new EventArgs());
// if you add an handler it will call it
testClass.MyButtonClick += myCustomHandler;
testClass.OnButtonClick(new EventArgs()); // myCustomHandler has been invoiked
}
private static void myCustomHandler(object sender, EventArgs e)
{
Console.WriteLine("myCustomHandler has been invoiked");
}
}
}
Well, the code you've given here:
public virtual void OnMyButtonClick(EventHandler e)
{
if (MyButtonClick!=null)
this.MyButtonClick(this, e);
}
isn't thread-safe. If the final subscription is removed after the nullity check but before the invocation, you could end up with a NullReferenceException (depending on whether the "raising" thread sees the change).
So you can change it to this instead:
public virtual void OnMyButtonClick(EventArgs e)
{
var handler = MyButtonClick;
if (handler != null)
{
handler(this, e);
}
}
... but of course you might forget to do that, and even if you don't, it's cumbersome to do that all over the place, IMO. So yes, while the benefit is "only" to avoid the nullity check, I'd say that's not a bad trade-off in many cases. Anything that makes it harder to make mistakes is a good idea, IMO.
Another alternative is to have an extension method:
public static void SafeInvoke(this EventHandler handler, object sender,
EventArgs e)
{
if (handler != null)
{
handler(sender, e);
}
}
Then change your calling code to:
public virtual void OnMyButtonClick(EventArgs e)
{
MyButtonClick.SafeInvoke(this, e);
}
(and use the same code for other events). You'd probably want a generic form for EventHandler<T> as well.
you don't need to do that. If the client that uses you class won't add an handler (subscriber) for MyButtonClick event the code won't throw an exception.
That is how events works (and delegates as there are the same thing) otherwise you would be forced to add an handler to all the events of a class (assuming there are any)
so you can do the below:
public virtual void OnMyButtonClick(EventArgs e)
{
MyButtonClick(this, e);
}
have a look at the example below:
public class TestClass
{
public event EventHandler MyButtonClick = delegate { };
public void ButtonClick(EventArgs e)
{
MyButtonClick(this,e);
}
}
class Program
{
static void Main(string[] args)
{
var testClass=new TestClass();
testClass.ButtonClick(new EventArgs());
// if you add an handler it will call it
testClass.MyButtonClick += myCustomHandler;
testClass.ButtonClick(new EventArgs()); // myCustomHandler has been invoiked
}
private static void myCustomHandler(object sender, EventArgs e)
{
Console.WriteLine("myCustomHandler has been invoiked");
}
}

Resources