As the answer by Greendrake says, if you have a  a legal reason, to enter property, you re not a trespasser. Trespassing is generally defined as entering on property against the expressed will of the owner or lawful occupant, **without lawful authority**. A firefighter is not trespassing when responding to a fire, even if the owner orders the firefighter to leave. A building inspector is not tresspassing while making an inspection (if local law grants an inspector access). Neither is a police officer with a warrant for entry, or a person with a court order to recover property.

In some cases such lawful authority must be communicated to the owner, in others it need not be, this depends on the nature of the authority and the exact provisions of the governing law.

Whether such a person entering with authority may be armed depends very much on the local law, and the nature of the authority. In some cases and some places such a person is free to be armed, in others this would be illegal.

If one is lawfully present somewhere and is attacked, one is entitled to defend oneself (or another), although there may be a duty to avoid a confrontation by retreating if this is reasonably possible when not in one's own home in some jurisdictions (such as California). But the use of deadly force (such as a gun) is generally not lawful unless there is an imminent threat of death or serious injury. None of this is legally different when one is lawfully on another's property than when one is in a public place.