How to create extension for VS2012 using VS Package on File Save Event - visual-studio-2012

I need to create an extension to do some custom activity, on File Save Event in visual studio. How to achieve this using VS Package.
I am struck with below code, any advise?
#region Package Members
FileEventsListener listener = null;
protected override void Initialize()
{
Debug.WriteLine (string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
base.Initialize();
listener = new FileEventsListener();
}
#endregion
}
public class FileEventsListener : IPersistFileFormat, IDisposable
{
private IVsSolution solution;
private uint solutionEventsCookie;
private bool isDirty;
private string fileName;
private const uint MyFormat = 0;
private const string MyExtension = ".edmx";
public FileEventsListener()
{
//solution = Package.GetGlobalService(typeof(SPersistFileFormat)) as IVsSolution;
//if (solution != null)
//{
// solution.AdviseSolutionEvents(this, out solutionEventsCookie);
//}
}
#region IDisposable Members
public void Dispose()
{
}
#endregion
public int GetClassID(out Guid pClassID)
{
ErrorHandler.ThrowOnFailure(((IPersist)this).GetClassID(out pClassID));
return VSConstants.S_OK;
}
public int GetCurFile(out string ppszFilename, out uint pnFormatIndex)
{
pnFormatIndex = MyFormat;
ppszFilename = fileName;
return VSConstants.S_OK;
}
public int GetFormatList(out string ppszFormatList)
{
char Endline = (char)'\n';
string FormatList = string.Format(CultureInfo.InvariantCulture, "My Editor (*{0}){1}*{0}{1}{1}", MyExtension, Endline);
ppszFormatList = FormatList;
return VSConstants.S_OK;
}
public int InitNew(uint nFormatIndex)
{
if (nFormatIndex != MyFormat)
{
return VSConstants.E_INVALIDARG;
}
// until someone change the file, we can consider it not dirty as
// the user would be annoyed if we prompt him to save an empty file
isDirty = false;
return VSConstants.S_OK;
}
public int IsDirty(out int pfIsDirty)
{
pfIsDirty = 0;
return VSConstants.S_OK;
}
public int Load(string pszFilename, uint grfMode, int fReadOnly)
{
fileName = pszFilename;
return VSConstants.S_OK;
}
public int Save(string pszFilename, int fRemember, uint nFormatIndex)
{
return VSConstants.S_OK;
}
public int SaveCompleted(string pszFilename)
{
return VSConstants.S_OK;
}
}
}

You can subscribe to the DTE.Events.DocumentEvents.DocumentSaved event.

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...
}

caling fragment method inside adapter but my value going null what should add?

This is my CartAdapter I called GetCart function in this adapter my function is calling successfully but my orgmst id and userid going null to database.
quantity.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
new GetUpdateQuantity().execute();
TwoFragment fragment = new TwoFragment();
fragment.Getcart();
if (quantity.length() == 0) {
} else {
quan = Double.parseDouble(quantity.getText().toString());
rate = Double.parseDouble(rate1.getText().toString());
total1 = Double.parseDouble(String.valueOf(rate * quan));
// convert double to string to get value
String show = Double.toString(total1);
//show in Textview
total.setText(show);
Log.d("<<<hcvyd", "" + show);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
----------
In myfragment i create method to send data to webservice this method i call in GetCart function then this function call inside adapter
MyFragment
'''GetCart Function'''
public void Getcart(){
String gh = orgmstid;
String hj = userid;
new GetCartItems().execute();
}
private class GetCartItems extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall("VIEW_CART", "F", "" + 'N' + "~" + orgmstid + "~" + userid);
Code for background CAll
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
import android.util.Log;
public class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... f_url) {
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
byte data[] = new byte[1024];
String file_string = "";
while ((count = input.read(data)) != -1) {
for (int i = 0; i < count; i++) {
file_string += (char) data[i];
}
}
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
// dismissDialog(progress_bar_type);
}
}
Code for calling
new DownloadFileFromURL().execute("URL");

issues with parcelable extension: getting unmarshalling unknown type code exception

long story short, I have one settlementItemeBase class as my father and two children. I want to make the father class parcelable so as extension happens, my two child classes be parcelable as well. I don't exactly know what I'm doing right or wrong. I searched little bit but nothing helped me.
here are my classes:
SettlementItemBase:
public class SettlementItemBase implements Parcelable{
public SettlementItemBase(){}
protected SettlementItemBase(Parcel in) {
}
public static final Creator<SettlementItemBase> CREATOR = new Creator<SettlementItemBase>() {
#Override
public SettlementItemBase createFromParcel(Parcel in) {
return new SettlementItemBase(in);
}
#Override
public SettlementItemBase[] newArray(int size) {
return new SettlementItemBase[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
}
}
first child class:
public class FirstClass extends SettlementItemBase {
private int id;
private int cardId;
private String cardNumber;
private String expDate;
private String currency;
private String url;
public FirstClass(){
id = 0;
cardId = 0;
cardNumber = "";
expDate = "";
currency = "";
url = "";
}
protected FirstClass(Parcel in) {
super(in);
id = in.readInt();
cardId = in.readInt();
cardNumber = in.readString();
expDate = in.readString();
currency = in.readString();
url = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeInt(cardId);
dest.writeString(cardNumber);
dest.writeString(expDate);
dest.writeString(currency);
dest.writeString(url);
}
public int getId() {
return id;
}
public int getCardId() {
return cardId;
}
public String getCardNumber() {
return cardNumber;
}
public String getExpDate() {
return expDate;
}
public String getCurrency() {
return currency;
}
public String getUrl() {
return url;
}
}
second child class:
public class SecondClass extends SettlementItemBase{
private int id;
private String currency;
private String accountNumber;
private String ibanNumber;
public SecondClass(int id, String currency,
String accountNumber, String ibanNumber){
this.id = id;
this.currency = currency;
this.accountNumber = accountNumber;
this.ibanNumber = ibanNumber;
}
protected SecondClass(Parcel in){
super(in);
id = in.readInt();
currency = in.readString();
accountNumber = in.readString();
ibanNumber = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(currency);
dest.writeString(accountNumber);
dest.writeString(ibanNumber);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCurrency() {
return currency;
}
public String getAccountNumber() {
return accountNumber;
}
public String getIbanNumber() {
return ibanNumber;
}
}
I'm passing and getting an ArrayList of both child class' items with intent putParcelableArrayListExtra and getParcelableArrayListExtra methods and get the following error:
Parcel android.os.Parcel#2d0fde33: Unmarshalling unknown type code 3276849 at offset 172
any help would be appreciated 3>
well I'm posting this for those who may run into the same problem as me.
the problem was solved after adding the Creator statement to the child classes.
for one of the child classes it would be like:
public static final Creator<FirstClass> CREATOR = new Creator<FirstClass>() {
#Override
public FirstClass createFromParcel(Parcel in) {
return new FirstClass(in);
}
#Override
public FirstClass[] newArray(int size) {
return new FirstClass[size];
}
};
hope this helps. 3>

Sending an object to host from a client

I cant seem to find the problem on the code but it the server is not displaying anything. It displays the catch. Client seems find and it sets the players name and score and sends it but I cant seem to find the issue on this one why server is not displaying the name and score.
Here is my Client:
public class Client
{
private static final int BUFSIZE = 64;
public static void main(String[] args) throws IOException
{
try
{
int scores;
Scanner in = new Scanner(System.in);
Socket clntSock = new Socket("127.0.0.1", 6000);
System.out.println("What is the filename?");
String input = in.nextLine();
Scanner fileInput = new Scanner(new File(input));
ObjectOutputStream out = new
ObjectOutputStream(clntSock.getOutputStream());
Player playerObject = new Player();
playerObject.setName(fileInput.nextLine());
System.out.println(""+playerObject.getName());
for (int i = 0; i < 5; i++)
{
scores = Integer.parseInt(fileInput.nextLine());
playerObject.setScore(scores);
System.out.println(""+playerObject.getScores().get(i));
}
out.writeObject(playerObject);
in.close();
fileInput.close();
out.close();
clntSock.close();
}
catch ( UnknownHostException ex )
{
System.out.println( "Unknown host" );
}
}
}
and my Host:
public class Host
{
private static final int BUFSIZE = 64;
public static void main(String[] args) throws IOException
{
// Step 1: Create a ServerSocket.
ServerSocket servSock = new ServerSocket(6000);
PrintStream fileOut = new PrintStream("Datafromclient.txt");
try
{
// Step 2: Wait for a connection..
Socket clntSock = servSock.accept();
// Step 3: Get input and output streams.
System.out.println("Step 3: Get object input stream.,");
ObjectInputStream objectIn = new
ObjectInputStream(clntSock.getInputStream());
Player playerObjct = (Player)objectIn.readObject();
System.out.println("The name of Player: "+playerObjct.getName());
for(int i=0; i <5; i++)
{
System.out.println("Scores:"+playerObjct.getScores().get(i));
}
objectIn.close();
clntSock.close();
// Step 5: Close connection
objectIn.close();
clntSock.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
System.err.println(e);
}
}
}
My player class:
public class Player
private String name;
private int playerId;
private int bestScore;
private static int numberOfPlayers = 0;
private ArrayList<Integer> scores = new ArrayList<Integer>();
/* -------------- CONSTRUCTOR --------------------------------------
*/
public Player()
{
numberOfPlayers++;
playerId = numberOfPlayers;
}
public Player(String name)
{
this.name = name;
}
//Create set method for setName
public void setName(String name)
{
this.name = name;
}
//Create set method for setScores
public void setScore(int score)
{
scores.add(score);
}
//Create get method for getPlayerId
public int getPlayerId()
{
return this.playerId;
}
//Create get method for getName
public String getName()
{
return this.name;
}
//Create get method for getScores
public ArrayList<Integer> getScores()
{
return scores;
}
//Create get method for getBestScore
public int getBestScore()
{
calculateBestScore();
return bestScore;
}
//Method to expose the value of numberOfPlayers
public static int getNumberOfPlayers()
{
return numberOfPlayers;
}
//Create get method for calcualteAverage
public double calculateAverage()
{
Integer sum = 0;
if(!scores.isEmpty())
{
for(Integer score : scores)
{
sum += score;
}
return sum.doubleValue() / scores.size();
}
return sum;
}
public void calculateBestScore()
{
bestScore = Collections.max(scores);
}
}
I was missing
import java.io.Serializable;
public class Player implements Serializable
now its working.

ManagementObjectCollection count property leaks?

Just recently a few colleagues of mine helped out with narrowing down a memory leak. One of the problems was found in Microsoft's code. This is from reflector showing that the enumerator will leak.
Here the count property calls getenumerator but never checks for Idisposable:
public int Count
{
get
{
if (this.isDisposed)
{
throw new ObjectDisposedException(name);
}
int num = 0;
IEnumerator enumerator = this.GetEnumerator();
while (enumerator.MoveNext())
{
num++;
}
return num;
}
}
This is the ManagementObjectCollection's GetEnumerator just to show the type returned is a ManagementObjectEnumerator.
public ManagementObjectEnumerator GetEnumerator()
{
if (this.isDisposed)
{
throw new ObjectDisposedException(name);
}
if (!this.options.Rewindable)
{
return new ManagementObjectEnumerator(this, this.enumWbem);
}
IEnumWbemClassObject ppEnum = null;
int errorCode = 0;
try
{
errorCode = this.scope.GetSecuredIEnumWbemClassObjectHandler(this.enumWbem).Clone_(ref ppEnum);
if ((errorCode & 0x80000000L) == 0L)
{
errorCode = this.scope.GetSecuredIEnumWbemClassObjectHandler(ppEnum).Reset_();
}
}
catch (COMException exception)
{
ManagementException.ThrowWithExtendedInfo(exception);
}
if ((errorCode & 0xfffff000L) == 0x80041000L)
{
ManagementException.ThrowWithExtendedInfo((ManagementStatus) errorCode);
}
else if ((errorCode & 0x80000000L) != 0L)
{
Marshal.ThrowExceptionForHR(errorCode);
}
return new ManagementObjectEnumerator(this, ppEnum);
}
This showing that it is disposable:
public class ManagementObjectEnumerator : IEnumerator, IDisposable
{
// Fields
private bool atEndOfCollection;
private uint cachedCount;
private IWbemClassObjectFreeThreaded[] cachedObjects;
private int cacheIndex;
private ManagementObjectCollection collectionObject;
private IEnumWbemClassObject enumWbem;
private bool isDisposed;
private static readonly string name;
// Methods
static ManagementObjectEnumerator();
internal ManagementObjectEnumerator(ManagementObjectCollection collectionObject, IEnumWbemClassObject enumWbem);
public void Dispose();
protected override void Finalize();
public bool MoveNext();
public void Reset();
// Properties
public ManagementBaseObject Current { get; }
object IEnumerator.Current { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; }
}
Though enumerators that are disposable are disposed of properly by foreach statements (http://msdn.microsoft.com/en-us/library/aa664754(v=vs.71).aspx), this does not mean that the only case where the enumerator will be used is in a foreach loop.
I know that you can skip the count property and roll your own mechanism for getting the number of objects in the collection by using the enumerator yourself but the question I have is how much unmanaged memory does this leak?

Resources